如果 table 不存在或更改它以添加新列,脚本的正确 SQL 服务器语法是什么?

What's the correct SQL Server syntax for a script that will create a table if it doesn't exist or else alter it to add new columns?

不确定我是否应该去 DBA.StackExchange,但我是一名软件开发人员,需要向现有后端数据库 table 添加列,并使用现有列 I, J 和 K(均为 INT 类型)。这样我的新前端代码就可以工作了。 table 有两个现有的外键 FK_T_U 和 FK_T_V,指的是其他相关的 tables U,V。我所做的就是添加三个新的 true/false BIT 列 (X, Y, Z) 到 table 但我需要一个脚本来执行此操作。很简单!我正在使用 SQL Server 2014。我们的源存储库中已经有一个 CREATE TABLE 脚本,我想我会用一个 IF EXISTS 和一个 ELSE 语句包围它并插入一个 ALTER TABLE 序列在中间。这样,未来的重新部署可以简单地改变现有的 table,或者如果它实际上不存在则创建它。好主意?我在到达那里时遇到了一些麻烦,所以我想通过在 Whosebug 上寻求帮助来加快这项工作。非常感谢您的协助!这是现有的 [有效] CREATE 脚本:

BEGIN TRANSACTION
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[T]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[T]
CREATE TABLE [dbo].[T] (
    [I] [int] IDENTITY (1, 1) NOT NULL ,
    [CourseK] [int] NULL ,
    [I] [int] NOT NULL ,
    [K] [int] NULL ,
    CONSTRAINT [PK_T] PRIMARY KEY  CLUSTERED 
    (
        [I]
    )  ON [PRIMARY] 
) ON [PRIMARY]
GRANT  SELECT  ON [dbo].[T]  TO [OtherApplication]
GRANT  SELECT ,  INSERT  ON [dbo].[T]  TO [AnotherApplication]

ALTER TABLE [dbo].[T] WITH NOCHECK ADD CONSTRAINT [FK_T_U] FOREIGN KEY 
    (
        [K]
    ) REFERENCES [U] (
        [K]
    )

ALTER TABLE [dbo].[T] WITH NOCHECK ADD CONSTRAINT [FK_T_V] FOREIGN KEY 
    (
        [I]
    ) REFERENCES [V] (
        [I]
    )

COMMIT TRANSACTION
BEGIN TRANSACTION

IF NOT EXISTS (SELECT * FROM sys.tables t WHERE t.name='T')
BEGIN
    CREATE TABLE [dbo].[T] (
        [I] [int] IDENTITY (1, 1) NOT NULL ,
        [CourseK] [int] NULL ,
        [I] [int] NOT NULL ,
        [K] [int] NULL ,
        CONSTRAINT [PK_T] PRIMARY KEY  CLUSTERED 
        (
        [I]
        )  ON [PRIMARY] 
    ) ON [PRIMARY]
    GRANT  SELECT  ON [dbo].[T]  TO [OtherApplication]
    GRANT  SELECT ,  INSERT  ON [dbo].[T]  TO [AnotherApplication]

    ALTER TABLE [dbo].[T] WITH NOCHECK ADD CONSTRAINT [FK_T_U] FOREIGN KEY 
    (
        [K]
    ) REFERENCES [U] ([K])

    ALTER TABLE [dbo].[T] WITH NOCHECK ADD CONSTRAINT [FK_T_V] FOREIGN KEY 
    (
        [I]
    ) REFERENCES [V] ([I])
END

IF NOT EXISTS (SELECT * FROM sys.tables t INNER JOIN sys.columns c ON t.object_id=c.object_id WHERE t.name='T' and c.name='X')
BEGIN
    ALTER TABLE [T] ADD [X] BIT;
END

IF NOT EXISTS (SELECT * FROM sys.tables t INNER JOIN sys.columns c ON t.object_id=c.object_id WHERE t.name='T' and c.name='y')
BEGIN
    ALTER TABLE [T] ADD [Y] BIT;
END

IF NOT EXISTS (SELECT * FROM sys.tables t INNER JOIN sys.columns c ON t.object_id=c.object_id WHERE t.name='T' and c.name='Z')
BEGIN
    ALTER TABLE [T] ADD [Z] BIT;
END

COMMIT TRANSACTION

我非常喜欢检查对象 ID...

IF (SELECT OBJECT_ID('DATABASENAME..TABLENAME')) IS NOT NULL
BEGIN
<DO THINGS HERE>
END