MSSQL to remove all foreign key constraint method

The Internet to find sql statement to delete a database to get all foreign key constraints statements

But found that it was just an inquiry, to be performed, then had to copy out the execution, more trouble

So wrote a sp to automate more convenient

code show as below:

 

Sql Code   Collection Code
  1. CREATE PROCEDURE sp_drop_all_fk  
  2.   
  3. as  
  4.   
  5. declare @sql varchar(255)  
  6. declare dropsql_cursor cursor for   
  7. select 'alter table '+object_name(fkeyid)+' drop constraint '+object_name(constid)+char(10) from sysreferences  
  8.   
  9. open dropsql_cursor  
  10.   
  11. fetch dropsql_cursor into @sql  
  12.   
  13. begin tran  
  14.   
  15. while @@fetch_status=0  
  16. begin  
  17.       
  18.     execute(@sql)  
  19.       
  20.     if @@error <> 0  
  21.     begin  
  22.         rollback  
  23.         return  
  24.     end  
  25.   
  26.     fetch dropsql_cursor into @sql  
  27.   
  28. end  
  29. deallocate dropsql_cursor  
  30.   
  31. commit  
  32. GO  

Reproduced in: https: //www.cnblogs.com/zhangchenliang/archive/2012/12/05/2802522.html

Guess you like

Origin blog.csdn.net/weixin_33858336/article/details/93495291
Recommended