如何在SQL Server中删除外键?

mma*_*tax 190 t-sql sql-server

我已经通过以下方式创建了一个外键(在SQL Server中):

alter table company add CountryID varchar(3);
alter table company add constraint Company_CountryID_FK foreign key(CountryID) 
references Country;
Run Code Online (Sandbox Code Playgroud)

然后我运行此查询:

alter table company drop column CountryID;
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

消息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;
Run Code Online (Sandbox Code Playgroud)

删除CountryID列需要做什么?

谢谢.

Mik*_*ike 298

尝试

alter table company drop constraint Company_CountryID_FK


alter table company drop column CountryID
Run Code Online (Sandbox Code Playgroud)


Jar*_*red 47

这将有效:

ALTER TABLE [dbo].[company] DROP CONSTRAINT [Company_CountryID_FK]
Run Code Online (Sandbox Code Playgroud)


小智 21

我想这会对你有所帮助......

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)
Run Code Online (Sandbox Code Playgroud)

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

  • 谢谢萨米尔。概括性强。 (2认同)

小智 19

首先检查约束是否存在然后丢弃它.

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
Run Code Online (Sandbox Code Playgroud)


boe*_*oes 10

alter table company drop constraint Company_CountryID_FK
Run Code Online (Sandbox Code Playgroud)