[英]Table already exists in a new SQL Server database
I'm writing a script to create a bunch of tables in SQL Server. 我正在编写脚本以在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
消息2714,级别16,状态6,服务器橙色,第22行
There is already an object named 'stuff' in the database.数据库中已经有一个名为“ stuff”的对象。
I run this on a Linux mint machine, a freshly installed SQL Server, and I use sqlcmd
. 我在Linux薄荷机,新安装的SQL Server上运行此程序,并使用
sqlcmd
。 I guess I can put a drop/delete
command before the creating the table, but this shouldn't happen to begin with. 我想我可以在创建表之前放置一个
drop/delete
命令,但这并不是刚开始的。 What is going on here? 这里发生了什么?
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. 当您从动态SQL执行
USE
语句时,当执行的批处理完成时,数据库上下文将恢复为原始数据库上下文(master?)。 You'll need to add a USE
to the CREATE TABLE
script and execute it using dynamic SQL too: 您需要将
USE
添加到CREATE TABLE
脚本中,并使用动态SQL来执行它:
SET @command = N'USE' + QUOTENAME(@db_name) + N';
CREATE TABLE stuff(
name VARCHAR(30) PRIMARY KEY NOT NULL,
weight INT,
quantity INT);
';
bind the create table statement inside a object existence check. 将create table语句绑定到对象存在检查中。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.