I am having problems with an older database creation script. I am wondering if it has anything to do with the way it is determining existence of certain objects.
For tables the line is
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tablename]' AND type in (N'U'))
BEGIN
Create table...
END
This seems wrong, after looking at sys.objects, I don't think it would ever have it there. Is this a bug? If so what would be a better way to write this?
I usually use
IF OBJECT_ID('dbo.TableName') IS NULL
CREATE Table dbo.TableName
.......
GO
OR you could do something like....
IF OBJECT_ID('dbo.TableName') IS NOT NULL
DROP TABLE dbo.TableName
GO
CREATE Table dbo.TableName
.......
GO
The OBJECT_ID()
function also takes a second (optional) parameters, it is the Object type, for user defined tables you would use U
, something like....
IF OBJECT_ID('dbo.TableName' , 'U') IS NULL
CREATE Table dbo.TableName
.......
GO
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.