如何在SQL Server中删除外键?

时间:2008-09-18 14:50:36

标签: sql-server tsql

我通过以下方式创建了一个外键(在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
  对象'Company_CountryID_FK'依赖于列'CountryID'   Msg 4922,Level 16,State 9,Line 2
  ALTER TABLE DROP COLUMN CountryID失败,因为一个或多个对象访问此列

我试过这个,但它似乎不起作用:

alter table company drop foreign key Company_CountryID_FK; 
alter table company drop column CountryID;

删除CountryID列需要做什么?

感谢。

8 个答案:

答案 0 :(得分:285)

尝试

alter table company drop constraint Company_CountryID_FK


alter table company drop column CountryID

答案 1 :(得分:45)

这将有效:

ALTER TABLE [dbo].[company] DROP CONSTRAINT [Company_CountryID_FK]

答案 2 :(得分:20)

我认为这会对你有所帮助......

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)

它将根据特定的表和列删除外键约束。

答案 3 :(得分:18)

首先检查是否存在约束然后删除它。

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

答案 4 :(得分:10)

alter table company drop constraint Company_CountryID_FK

答案 5 :(得分:4)

我不知道MSSQL但它不会是:

alter table company drop **constraint** Company_CountryID_FK;

答案 6 :(得分:1)

您也可以右键单击表格,选择修改,然后转到属性,右键单击它,然后选择删除主键。

答案 7 :(得分:1)

您是要删除FK约束还是列本身?

删除约束:

alter table company drop constraint Company_CountryID_FK

在删除约束之前,您将无法删除列。