修改数据库相关字段的默认值
原来的数据库有好多类型的数据默认值都是
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
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
小记
-----
注册好以后基本就没有来过,以后会把自己学习的点点都记在这边。记录自己成长。