ALTER TABLE DROP COLUMN failed because one or more objects access this column

前端 未结 7 1555
[愿得一人]
[愿得一人] 2020-12-05 22:26

I am trying to do this:

ALTER TABLE CompanyTransactions DROP COLUMN Created

But I get this:

Msg 5074, Level 16, Stat

7条回答
  •  有刺的猬
    2020-12-05 23:01

    You need to do a few things:

    1. You first need to check if the constrain exits in the information schema
    2. then you need to query by joining the sys.default_constraints and sys.columns if the columns and default_constraints have the same object ids
    3. When you join in step 2, you would get the constraint name from default_constraints. You drop that constraint. Here is an example of one such drops I did.
    -- 1. Remove constraint and drop column
    IF EXISTS(SELECT *
              FROM INFORMATION_SCHEMA.COLUMNS
              WHERE TABLE_NAME = N'TABLE_NAME'
                AND COLUMN_NAME = N'LOWER_LIMIT')
       BEGIN
        DECLARE @sql NVARCHAR(MAX)
        WHILE 1=1
            BEGIN
                SELECT TOP 1 @sql = N'alter table [TABLE_NAME] 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('[TABLE_NAME]') AND c.name = N'LOWER_LIMIT'
                IF @@ROWCOUNT = 0
                    BEGIN
                        PRINT 'DELETED Constraint on column LOWER_LIMIT'
                        BREAK
                    END
            EXEC (@sql)
        END;
        ALTER TABLE TABLE_NAME DROP COLUMN LOWER_LIMIT;
        PRINT 'DELETED column LOWER_LIMIT'
       END
    ELSE
       PRINT 'Column LOWER_LIMIT does not exist'
    GO
    

提交回复
热议问题