我已经通过以下方式创建了一个外键(在SQL Server中):
alter table company add CountryID varchar(3); alter table company add constraint Company_CountryID_FK foreign key(CountryID) references Country;
然后我运行此查询:
alter table company drop column CountryID;
我收到此错误:
消息5074,级别16,状态4,行2
对象'Company_CountryID_FK'依赖于列'CountryID'.
消息4922,级别16,状态9,行2
ALTER TABLE DROP COLUMN CountryID失败,因为一个或多个对象访问此列
我试过这个,但它似乎不起作用:
alter table company drop foreign key Company_CountryID_FK; alter table company drop column CountryID;
删除CountryID
列需要做什么?
谢谢.
尝试
alter table company drop constraint Company_CountryID_FK alter table company drop column CountryID
这将有效:
ALTER TABLE [dbo].[company] DROP CONSTRAINT [Company_CountryID_FK]
我想这会对你有所帮助......
DECLARE @ConstraintName nvarchar(200) SELECT @ConstraintName = KCU.CONSTRAINT_NAME FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU ON KCU.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG AND KCU.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA AND KCU.CONSTRAINT_NAME = RC.CONSTRAINT_NAME WHERE KCU.TABLE_NAME = 'TABLE_NAME' AND KCU.COLUMN_NAME = 'TABLE_COLUMN_NAME' IF @ConstraintName IS NOT NULL EXEC('alter table TABLE_NAME drop CONSTRAINT ' + @ConstraintName)
它将根据特定的表和列删除外键约束.
首先检查约束是否存在然后丢弃它.
if exists (select 1 from sys.objects where name = 'Company_CountryID_FK' and type='F') begin alter table company drop constraint Company_CountryID_FK end
alter table company drop constraint Company_CountryID_FK