问题
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:
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
来源:https://stackoverflow.com/questions/56689885/sql-server-flyway-script-drop-column-constraint-issue