具有不存在的列的条件脚本(还)?

时间:2018-12-16 16:13:03

标签: sql-server

我正在使用SQL Server创建要在生产环境中运行的脚本。

如果表不包含特定列,则创建该列。

我已经做到了:

IF NOT EXISTS (
       SELECT 1
       FROM   INFORMATION_SCHEMA.columns
       WHERE  COLUMN_NAME = 'SeeMaxDaysBackwardPrice'
              AND TABLE_NAME = 'tblsubscriptiontype'
   )
BEGIN

    ALTER TABLE dbo.tblsubscriptiontype ADD SeeMaxDaysBackwardPrice INT NULL

END

但是现在我想在修改后的表中插入新行。所以现在我的脚本看起来像这样:

IF NOT EXISTS (
       SELECT 1
       FROM   INFORMATION_SCHEMA.columns
       WHERE  COLUMN_NAME = 'SeeMaxDaysBackwardPrice'
              AND TABLE_NAME = 'tblsubscriptiontype'
   )
BEGIN


    ALTER TABLE dbo.tblsubscriptiontype ADD SeeMaxDaysBackwardPrice INT NULL


    SET IDENTITY_INSERT [dbo].[tblSubscriptionType] ON;

    BEGIN TRANSACTION

    INSERT INTO [dbo].[tblSubscriptionType]
      (
       ...
        [SeeMaxDaysBackwardPrice]      <-------- ERROR
      )
    SELECT ...
           -365


    COMMIT;
    RAISERROR (
        N'[dbo].[tblSubscriptionType]: Insert Batch: 1.....Done!',
        10,
        1
    ) 
    WITH NOWAIT;


    SET IDENTITY_INSERT [dbo].[tblSubscriptionType] OFF;
END
GO

但是现在我得到一个错误(我完全理解):

Msg 207, Level 16, State 1, Line 29
Invalid column name 'SeeMaxDaysBackwardPrice'.

当然,我可以将脚本分成2个单独的脚本,但是我会两次遇到这种情况:

IF NOT EXISTS (
       SELECT 1
       FROM   INFORMATION_SCHEMA.columns
       WHERE  COLUMN_NAME = 'SeeMaxDaysBackwardPrice'
              AND TABLE_NAME = 'tblsubscriptiontype'
   )

问题:

是否有任何方法可以使不存在的列的SQL更轻松? (我已经知道动态查询(文本),但是我想知道是否还有其他选择。

1 个答案:

答案 0 :(得分:1)

只需将代码包装在动态T-SQL语句中即可:

IF NOT EXISTS (
       SELECT 1
       FROM   INFORMATION_SCHEMA.columns
       WHERE  COLUMN_NAME = 'SeeMaxDaysBackwardPrice'
              AND TABLE_NAME = 'tblsubscriptiontype'
   )
BEGIN


    ALTER TABLE dbo.tblsubscriptiontype ADD SeeMaxDaysBackwardPrice INT NULL


    SET IDENTITY_INSERT [dbo].[tblSubscriptionType] ON;


    DECLARE @DynamicTSQLStatement NVARCHAR(MAX);

    SET @DynamicTSQLStatement = N'

     INSERT INTO [dbo].[tblSubscriptionType]
      (
       ...
        [SeeMaxDaysBackwardPrice]      
      )
    SELECT ...
           -365

    ';

    BEGIN TRY

        BEGIN TRAN;

        EXEC sp_executesql @DynamicTSQLStatement; 

        COMMIT TRAN;

    END TRY
    BEGIN CATCH

        ROLLBACK TRAN;

    END CATCH




    SET IDENTITY_INSERT [dbo].[tblSubscriptionType] OFF;
END
GO