如何在SQL Server中删除外键?
问题描述:
我已经创建了一个外键(在SQL Server):如何在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;
,我得到这个错误:
Msg 5074, Level 16, State 4, Line 2
The object 'Company_CountryID_FK' is dependent on column 'CountryID'.
Msg 4922, Level 16, State 9, Line 2
ALTER TABLE DROP COLUMN CountryID failed because one or more objects access this column
我有试过这个,但它似乎不工作:
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
答
我不知道MSSQL,但岂不是:
alter table company drop **constraint** Company_CountryID_FK;
答
alter table company drop constraint Company_CountryID_FK
答
这将工作:
ALTER TABLE [dbo].[company] DROP CONSTRAINT [Company_CountryID_FK]
答
您也可以右键点击在表格中选择修改,然后转到属性,右键单击它并选择放下主键。
答
您是否试图删除FK约束或列本身?
删除约束:
alter table 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
你试图放弃外键是什么错误? – ddc0660 2008-09-18 14:55:39
请注意,放弃外键约束并不知道它为何存在于第一个位置是危险的。如果你刚刚创建了这个,并且错误地使用了其他答案中提供的代码。如果没有,那么不要放弃约束,直到确定不会因为这样做而破坏其他东西。创建约束是为了强制执行公用规则,最好确保在删除它们之前不再需要它们。 – HLGEM 2008-09-18 17:42:07