我正在使用sql server 2005。 我正在编写一个T sql脚本,需要在数据库中添加一个表, 但我想添加检查表是否已创建表。 但我的脚本给了我这个错误信息:
Msg 102, Level 15, State 1, Line 7
Incorrect syntax near 'ON'.
Msg 2714, Level 16, State 6, Line 1
There is already an object named 'DeliveryChargeRegion' in the database.
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near 'END'.
答案 0 :(得分:1)
IF not EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TABLENAME]') AND type in (N'U'))
begin
-- Create table.
end
GO
答案 1 :(得分:1)
此代码类似于SSMS生成的代码:
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[TABLE_NAME_HERE]') AND type in (N'U'))
BEGIN
-- CREATE TABLE HERE
END
答案 2 :(得分:1)
另一种方法
if object_id('tablename') is NULL
BEGIN
CREATE TABLE tableName
END
sys.objects方法没什么问题,我发现上面的内容更容易编写和阅读......