SQL Server去除外键的存储过程

发布时间:2019-12-12编辑:脚本学堂
SQL Server去除外键的存储过程

创建一个去除SQL Server外键的存储过程
 

复制代码 代码如下:

create proce prdropforeignkeys
@chvreferencedtable varchar(30)
as
 declare @chvtablewithforeignkey varchar(30),
            @chvforeignkey varchar(30),
            @chvsql varchar(255)
declare cufks cursor for
 select  tb.name,fk.name from
((sysobject tb inner join sysreferences r on tb.id=r.fkeyid)
  inner join sysobjects fk on r.constid=fk.id)
  inner join sysobjects refd on refd_tb.id=r.rkeyid)
 where refd_tb.name=@chvreferencedtable
 open cufks
 fetch next from cufks into @chvtablewithforeignkey,@chvforeignkey

 while (@@fetch_status<>-1)
 begin
  select @chvsql='alter table'+@chvtablewithforeignkey+'drop constraint '+@chvforeignkey
  exec(@chvsql)
 fetch next from cufks into @chvtablewithforeignkey,@chvforeignkey
end
 deallocate cufks