天马行空(笨笨)
希望下辈子不要那么笨了
删除某字段的所有关系  
 
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='表名'    
           and  a.name='字段名'  
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='表名'  
           and  d.name='字段名'  
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='表名'  
           and  d.name='字段名'  
 
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  
 
--再删除字段  
alter  table  表名  drop  column  字段名
posted on 2007-05-10 11:16  天马行空(笨笨)  阅读(218)  评论(0)    收藏  举报