首先检查表是否存在,如果不存在则创建。
IF NOT EXISTS (SELECT 1 FROM sys.tables WHERE [object_id] = OBJECT_ID(N'dbo.UserProfile', N'U'))
BEGIN
CREATE TABLE [dbo].[UserProfile] (
[FirstName] VARCHAR(150) NOT NULL,
[LastName] VARCHAR(150) NOT NULL,
[Email] VARCHAR(150) NOT NULL
)
END
然后检查您需要的每个单独的列是否存在并处理这些
IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE [name] = 'FirstName' AND [object_id] = OBJECT_ID(N'dbo.UserProfile', N'U'))
BEGIN
ALTER TABLE dbo.UserProfile
ADD [FirstName] VARCHAR(150) NOT NULL
END
IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE [name] = 'LastName' AND [object_id] = OBJECT_ID(N'dbo.UserProfile', N'U'))
BEGIN
ALTER TABLE dbo.UserProfile
ADD LastName VARCHAR(150) NOT NULL
END
IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE [name] = 'Email' AND [object_id] = OBJECT_ID(N'dbo.UserProfile', N'U'))
BEGIN
ALTER TABLE dbo.UserProfile
ADD Email VARCHAR(150) NOT NULL
END