0

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.

2
  • Put the GO after the Create database. Also, in the second example, you probably have table_name created in the Master database and you don't USE db_name before the Create Table statement. Commented Nov 9, 2017 at 22:59
  • i was use db_name before create table but the go statement after create database fixed my issue thanks! Commented Nov 9, 2017 at 23:06

1 Answer 1

2

Why don't you use

USE MASTER
GO
DROP DATABASE IF EXISTS db_name

before creating db ?

Sign up to request clarification or add additional context in comments.

3 Comments

There is already an object named 'table_name' in the database.
DROP TABLE IF EXISTS table_name
Perhaps the connection string is not using the right db ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.