如何在SQL Server中删除外键?
我已经创build了一个外键(在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
我不知道MSSQL,但它不会是:
alter table company drop **constraint** Company_CountryID_FK;
您也可以右键单击表格,select修改,然后转到属性,右键单击它,然后select删除主键。
你想要放弃FK约束或列本身?
删除约束:
alter table company drop constraint Company_CountryID_FK
删除约束之前,您将无法删除该列。