SQL Server Flyway脚本-删除列约束问题

时间:2019-06-20 16:01:22

标签: database constraints flyway alter

我正在使用SQL Server,正在尝试删除一列。 表模式如下:

CREATE TABLE [dbo].[XYZ](
    [ID] [int] NOT NULL,
    [DSC] [varchar](255) NULL,
    [LOWER_LIMIT] [int] NOT NULL,
    [UPPER_LIMIT] [int] NOT NULL,
CONSTRAINT [XP_XYZ] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

当我尝试删除列时:

ALTER TABLE [SENSOR]
  DROP COLUMN LOWER_LIMIT;

我被要求在之前取消约束

The object 'DF__SENSOR__LOWER_LI__08B54D69' is dependent on column 'LOWER_LIMIT'.
    Msg 4922, Level 16, State 9, Line 45
    ALTER TABLE DROP COLUMN LOWER_LIMIT failed because one or more objects access this column.

现在,我正在编写用于删除列的flyway脚本,直到运行更高级别的环境中约束更改时,我才尝试运行drop命令,才知道约束。我如何起草飞行路线以删除此专栏?

1 个答案:

答案 0 :(得分:0)

最后,在Stackoverflow的帮助下,我能够执行以下操作:

     IF EXISTS(SELECT *
          FROM INFORMATION_SCHEMA.COLUMNS
          WHERE TABLE_NAME = N'SENSOR'
            AND COLUMN_NAME = N'LOWER_LIMIT')
   BEGIN
    DECLARE @sql NVARCHAR(MAX)
    WHILE 1=1
        BEGIN
            SELECT TOP 1 @sql = N'alter table [SENSOR] drop constraint ['+dc.name+N']'
            FROM sys.default_constraints dc
            JOIN sys.columns c
            ON c.default_object_id = dc.object_id
            WHERE dc.parent_object_id = OBJECT_ID('[SENSOR]') AND c.name = N'LOWER_LIMIT'
            IF @@ROWCOUNT = 0 
                BEGIN
                    PRINT 'DELETED Constraint on column LOWER_LIMIT' 
                    BREAK
                END
        EXEC (@sql)
    END;
    ALTER TABLE [SENSOR] DROP COLUMN LOWER_LIMIT;
    PRINT 'DELETED column LOWER_LIMIT' 
   END
ELSE
   PRINT 'Column LOWER_LIMIT does not exist'
GO

原始帖子为here