删除数据库中所有外键

来源:互联网 发布:考试作弊专用笔淘宝 编辑:程序博客网 时间:2024/04/30 10:26

If Exists (Select * From sysobjects Where id = object_id(N'[dbo].[sp_DropAllForeignKey]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
Drop Procedure [dbo].[sp_DropAllForeignKey]
GO
Create Procedure [dbo].[sp_DropAllForeignKey]
AS
 Declare @sql nvarchar(4000),@TableName nvarchar(128),@FKName nvarchar(256)
 Declare cursor_ForeignKey Cursor For
 Select A.Name AS FKName,B.Name AS TableName
 From sys.sysobjects A
  inner join
    ( Select ID,Name From sys.sysobjects Where Type='U'
   ) B
 On A.Parent_obj =B.ID And A.Type='F'
 Order by B.Name
 
 --Open cursor
 Open cursor_ForeignKey
 Fetch Next From cursor_ForeignKey into @FKName,@TableName
 While @@FETCH_STATUS=0
 Begin
  Set @Sql='Alter Table [dbo].['+@TableName+'] Drop CONSTRAINT ['+@FKName+']'
  Execute(@Sql)
  Fetch Next From cursor_ForeignKey into @FKName,@TableName
 End
 Close cursor_ForeignKey
 Deallocate cursor_ForeignKey
GO

 

 

原创粉丝点击