删除表字段的sql语句

哎,还是上周的事情了,csdn的博客最近咋老是打不开呢!

基本语句:Alter table 表名 drop Column 字段名

另单单是这样是不行滴,还要删除对应的关系滴。下面就把查找到的那篇文章引用下吧!

原文地址:http://hi.baidu.com/lisky119/blog/item/3c348c082573949c0a7b82d1.html

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:   lw
-- Create date: 2009-07-31
-- Description: 强行删除表列,【无错误】【删除表的列之前一定要删除依赖,索引】,不然会报很多错误
-- =============================================
alter PROCEDURE [dbo].[Delete_Column_Constraint]
(
@tablename nvarchar(50),
@columnname nvarchar(50)
)
AS

--删除某字段的所有关系  

declare   tb   cursor   local   for  
--默认值约束  
select   sql='alter   table   ['+b.name+']   drop   constraint   ['+d.name+']'  
from   syscolumns   a  
join   sysobjects   b   on   a.id=b.id  
join   syscomments   c   on   a.cdefault=c.id  
join   sysobjects   d   on   c.id=d.id  
where   b.name = @tablename  
and   a.name = @columnname  
union   all   --外键引用  
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  
join   sysobjects   e   on   e.id=a.rkeyid  
join   syscolumns   f   on   f.id=e.id   and   a.rkey=f.colid    
where   e.name = @tablename
and   d.name = @columnname
union   all --索引  
select   case   e.xtype   when   'PK'   then   'alter   table   ['+c.name+']   drop   constraint   ['+e.name+']'  
else   '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<>'dtproperties'  
join   syscolumns   d   on   b.id=d.id   and   b.colid=d.colid  
join   sysobjects   e   on   c.id=e.parent_obj  
where   a.indid   not   in(0,255)  
and   c.name='a'  
and   d.name='id'  
   
declare   @s   varchar(8000)  
open   tb  
fetch   next   from   tb   into   @s  
while   @@fetch_status=0  
begin  
exec(@s)  
fetch   next   from   tb   into   @s  
end  
close   tb  
deallocate   tb

DECLARE @SQL AS nvarchar(500)
set @SQL = 'Alter table ' + @tablename + ' Drop Column ' + @columnname
EXECUTE sp_executesql @SQL
GO

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值