Jessie Cryer
Jessie Cryer

Reputation: 179

Create and use database using t-sql in visual studio

I'm trying to write a single sql script that creates a database, selects it, and then creates the tables for the database but I'm having trouble making this work in visual studio. This is what I'm trying:

create database db_name;

use db_name;
go

create table table_name (
...
);

This gives me an error message "Database db_name does not exist" and in fact this script doesn't create the database. However, if I do not try to use it ie.

create database db_name;
create table table_name (
...
);

I get an error saying "There is already an object named 'table_name' in the database, but it doesn't create the table at all. I'm assuming for whatever reason it's targeting another old database that I have. I don't know how to specify which database to create the table for using the second method and I'm not having any luck selecting the newly created database using the first method.

Upvotes: 0

Views: 33

Answers (1)

Zulander
Zulander

Reputation: 824

Why don't you use

USE MASTER
GO
DROP DATABASE IF EXISTS db_name

before creating db ?

Upvotes: 2

Related Questions