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

前端 未结 7 1625
[愿得一人]
[愿得一人] 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:06

    The @SqlZim's answer is correct but just to explain why this possibly have happened. I've had similar issue and this was caused by very innocent thing: adding default value to a column

    ALTER TABLE MySchema.MyTable ADD 
      MyColumn int DEFAULT NULL;
    

    But in the realm of MS SQL Server a default value on a colum is a CONSTRAINT. And like every constraint it has an identifier. And you cannot drop a column if it is used in a CONSTRAINT.

    So what you can actually do avoid this kind of problems is always give your default constraints a explicit name, for example:

    ALTER TABLE MySchema.MyTable ADD 
      MyColumn int NULL,
      CONSTRAINT DF_MyTable_MyColumn DEFAULT NULL FOR MyColumn;
    

    You'll still have to drop the constraint before dropping the column, but you will at least know its name up front.

提交回复
热议问题