码迷,mamicode.com
首页 > 数据库 > 详细

删除sql数据库列存储过程包括关系

时间:2017-10-10 13:24:07      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:for   and   int   exe   when   nbsp   --   open   column   

SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
GO
create proc spDropColumn
  @tbname sysname, --要处理的表名
  @fdname sysname, --要处理的字段名
  @delfield bit=1 --0只删除关系,1同时删除字段
as
SET ANSI_WARNINGS OFF
declare @t table (sql nvarchar(2000))
insert into @t
  --默认值约束
  select sql=‘alter table [‘+b.name+‘] drop constraint [‘+d.name+‘]‘
  from syscolumns a
  join sysobjects b on a.id=b.id and a.name=@fdname and b.name=@tbname  
  join syscomments c on a.cdefault=c.id
  join sysobjects d on c.id=d.id
  union --外键引用
  select s=‘alter table [‘+c.name+‘] drop constraint [‘+b.name+‘]‘ 
  from sysforeignkeys a
  join sysobjects b on b.id=a.constid
  join sysobjects c on c.id=a.fkeyid
  join syscolumns d on d.id=c.id and a.fkey=d.colid and d.name=@fdname
  join sysobjects e on e.name=@tbname
  --join syscolumns f on f.id=e.id and a.rkey=f.colid  
  union --主键/唯一键/索引
  select case when e.xtype in(‘PK‘,‘UQ‘) then ‘alter table [‘+c.name+‘] drop constraint [‘+e.name+‘]‘
  else ‘if exists(select * from sysindexes where ID=object_id(‘‘‘+c.name+‘‘‘) and Name=N‘‘‘+a.name+‘‘‘ and root <>0) drop index [‘+c.name+‘].[‘+a.name+‘]‘ end
  from sysindexes a
  join sysindexkeys b on a.id=b.id and a.indid=b.indid
  join sysobjects c on b.id=c.id and c.xtype=‘U‘ and c.name=@tbname
  join syscolumns d on b.id=d.id and b.colid=d.colid and d.name=@fdname
  left join sysobjects e on e.id=object_id(a.name)
  where a.indid not in(0,255)
 declare @sql nvarchar(2000)
 declare p cursor for select sql from @t
 open p
 fetch next from p into @sql
  while (@@fetch_status = 0)
 begin
 execute (@sql)
 fetch next from p into @sql
 end
 close p
 deallocate p
if @delfield=1
 if exists(select * from syscolumns where id in (select id from sysobjects where name=@tbname) and name=@fdname)
     exec(‘alter table [‘+@tbname+‘] drop column [‘+@fdname+‘]‘)
SET ANSI_WARNINGS ON
GO

删除sql数据库列存储过程包括关系

标签:for   and   int   exe   when   nbsp   --   open   column   

原文地址:http://www.cnblogs.com/panguan/p/7644856.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!