tags:

views:

15

answers:

3

I am working on sql server 2005. I am writing a T sql script which will need to add a table to the database, but i want to add the check that if the table is already created. But my script is giving me this error message:

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'.
+1  A: 
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

ps
+1  A: 

This code is similar to that generated by 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
Cade Roux
+1  A: 

Another approach

if object_id('tablename') is NULL
BEGIN
    CREATE TABLE tableName

END

Nothing wrong with the sys.objects approach, I just find the above easier to write and read...

Sparky
I dont think it checks specifically for tables. It could be any kind of object with that name.
ps
Oh, it definitely doesn't, it is any kind of database object, good point, thanks...
Sparky
is the error message limited to tables?
Nick
Not a error message, simply that if an object is undefined, it's object id is NULL. You can use the code example above to check for stored procedures, functions, etc.
Sparky