Reputation: 10685
I'm writing a script to create a bunch of tables in SQL Server. As I write the script, I want to create and delete the database. The problem is that the I get an error saying that the object already exists.
Here is my example script
DECLARE @db_name varchar(20);
DECLARE @command varchar(100);
SET @db_name='testdb';
SET @command='DROP DATABASE ' + @db_name
IF EXISTS(SELECT * FROM sys.databases WHERE name=@db_name)
exec(@command)
SET @command='CREATE DATABASE ' + @db_name
EXEC(@command)
--listing databaes
SELECT name from master.dbo.sysdatabases
-- using our database
SET @command='USE ' + @db_name
EXEC(@command)
PRINT 'listing tables'
SET @command = 'SELECT table_name FROM ' + @db_name + '.INFORMATION_SCHEMA.TABLES WHERE table_type = "base TABLE"'
EXEC(@command)
CREATE TABLE stuff(
name VARCHAR(30) PRIMARY KEY NOT NULL,
weight INT,
quantity INT)
and the output I get is
name
------------
master
tempdb
model
msdb
testdb
SW
(6 rows affected)
listing tables
table_name
Error:
Msg 2714, Level 16, State 6, Server Orange, Line 22
There is already an object named 'stuff' in the database.
I run this on a Linux mint machine, a freshly installed SQL Server, and I use sqlcmd
. I guess I can put a drop/delete
command before the creating the table, but this shouldn't happen to begin with. What is going on here?
Upvotes: 1
Views: 1664
Reputation: 46233
When you execute a USE
statement from dynamic SQL, the database context reverts back to the original database context (master?) when the executed batch completes. You'll need to add a USE
to the CREATE TABLE
script and execute it using dynamic SQL too:
SET @command = N'USE' + QUOTENAME(@db_name) + N';
CREATE TABLE stuff(
name VARCHAR(30) PRIMARY KEY NOT NULL,
weight INT,
quantity INT);
';
Upvotes: 2
Reputation: 8043
bind the create table statement inside a object existence check. like this
IF OBJECT_ID('stuff') IS NULL
BEGIN
CREATE TABLE stuff(
name VARCHAR(30) PRIMARY KEY--NOT NULL is not needed as the primary key does not allow NULL,
weight INT,
quantity INT)
END
Upvotes: 0