SQL删除外键约束

SQL删除外键约束

ZKEASOFT March 03, 2017


使用如下SQL语句查询出表中外键约束名称:

 select name  
 from  sys.foreign_key_columns f join sys.objects o on f.constraint_object_id=o.object_id 
 where f.parent_object_id=object_id('表名')

判断是否存在再删除:

IF EXISTS ( select  name
            FROM    sys.foreign_key_columns f
                    JOIN sys.objects o ON f.constraint_object_id = o.object_id
            WHERE   f.parent_object_id = OBJECT_ID('FN_FootNote')
                    AND name = N'CMS_ContentItem_FN_FootNote_ProductFK' )
    BEGIN
       ALTER TABLE dbo.FN_FootNote DROP CONSTRAINT CMS_ContentItem_FN_FootNote_ProductFK;
    END;

微信公众号