sql server刪除外鍵約束

字號:


    x先找出約束名字
    然后刪除它
    我給個例子
    --測試環(huán)境
    --主表
    create table test1(id int primary key not null,value int)
    insert test1 select 1,2
    go
    --從表
    create table test2(id int references test1(id),value int)
    go
    --第一步:找出test2表上的外鍵約束名字
    --2000
    exec sp_helpconstraint 'test2'
    --可以在constraint_name 屬性中找到外鍵約束名字
    --2005
    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('test2')
    /*
    name
    ---------------------------------
    fk__test2__id__08ea5793*/
    --第二步:刪除外鍵約束
    alter table test2 drop constraint fk__test2__id__08ea5793
    --第三步:檢查表上是否還有外鍵約束
    --只要使用第一步里面的查找語句即可