现在的位置: 首页 > 综合 > 正文

批量修改系统中int,varchar字段的默认值

2013年05月16日 ⁄ 综合 ⁄ 共 1226字 ⁄ 字号 评论关闭

declare @t table(id int identity(1,1),tbname varchar(256), colname varchar(256),xtype varchar(20))
insert into @t
select a.name,b.name ,c.name
from sysobjects a
   
inner join syscolumns  b on a.id=b.id
   
inner join systypes  c on b.xusertype = c.xusertype 
where a.xtype='u'
 
and c.name in ('varchar','int')
 
and b.status<>0x80  --去掉自增列  
  and not exists  --过滤掉原来已存在默认值的列
     (select 1
     
from
          (
select
                (
select name from sysobjects where id=c.id) 表名,
                (
select name from syscolumns where cdefault=a.id) 字段名
          
from  sysobjects b,syscolumns c,syscomments a
          
where b.xtype='d'
            
and a.id=b.id
            
and b.parent_obj=c.id
            
and a.colid=c.colid
           ) t
     
where a.name=t.表名
       
and b.name=t.字段名)
--select * from @t
declare @i int
set @i=1
declare @tbname varchar(256),@colname varchar(256),@xtype varchar(20),@sql nvarchar(4000)
while @i <= (select MAX(id) from @t)
begin
   
select @tbname=tbname,@colname=colname,@xtype = xtype from @t where id=@i
   
set @sql = 'alter table ['+@tbname+'] add constraint ' +  'df_' + replace(@tbname,'-','') +'_'+ replace(@colname,'-','') + ' default '
   
if @xtype = 'int'
   
begin
       
set @sql = @sql + ' 0 '
   
end
   
else if @xtype = 'varchar'
   
begin
       
set @sql = @sql + ''''''
   
end
   
set @sql = @sql + ' for [' + @colname +']'
   
exec(@sql)
   
set @i = @i + 1
end

抱歉!评论已关闭.