SQL Server Flyway script - drop column constraint

2019-08-17 14:25发布

I'm working on SQL Server and am trying to drop a column. The table schema is as below:

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

When I attempt to drop the column :

ALTER TABLE [SENSOR]
  DROP COLUMN LOWER_LIMIT;

I'm asked to drop the constraint before:

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.

Now I'm writing a flyway script to drop the column and I would not know the constraint until I run the drop command as the constraint changes in higher environments I attempt to drop the column. How do I draft my flyway to drop this column?

1条回答
我想做一个坏孩纸
2楼-- · 2019-08-17 15:12

Finally with the help of Stackoverflow's help I was able to do something like this:

     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

The original post is here

查看更多
登录 后发表回答