原來的數據庫有好多類型的數據默認值都是
null
值,為以後在實際開發過程中帶了好多不變。這個null其實也有好處,我想可以節省數據庫的空間,在新增數據的時候還可以提高速度。不過還是應領導要求寫了下面的代碼。在CSDN的大俠幫助下完成的。
代碼
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