表A
字段1 字段2 字段3 字段4 字段N ------ 字段为动态表生成的,所以N不定NULL null 要求:在表中所有字段中,如果有NULL,则更新为0语句:Update A set ......,set后面的怎么写?如果用case一个个列举的话,不符合动态表的原则,字段数无法事先知道的
字段1 字段2 字段3 字段4 字段N ------ 字段为动态表生成的,所以N不定NULL null 要求:在表中所有字段中,如果有NULL,则更新为0语句:Update A set ......,set后面的怎么写?如果用case一个个列举的话,不符合动态表的原则,字段数无法事先知道的
--直接动态修改字段类型,加默认值
alter table tb alter column 字段 default 0 not null
create table testtb1(id int ,nn varchar(20))
insert into testtb1
select null,null union all
select null,'a' union all
select 2,null declare @tablename varchar(200) set @tablename ='testtb1'
declare @sql varchar(8000) set @sql=''
select @sql=@sql+','+name+'=isnull('+name+',0)'
from syscolumns where id=object_id(@tablename) order by colid
set @sql=stuff(@sql,1,1,'')
exec('update '+@tablename+' set ' +@sql)select * from testtb1
/*
id nn
----------- --------------------
0 0
0 a
2 0
*/
set @sql+=stuff((select ','+name+'=isnull('+name+',0)' from sys.all_columns where user_type_id=56 and object_id=object_id('t') for xml path('')),1,1,'')
select @sql
--新手上路
declare @sql varchar(max)
declare @t varchar(255)set @t='表名'
select @sql=isnull(@sql,'')+'update '+@t+' set ' +name+'=0 where '+name+'= null
'
from (
select distinct name from syscolumns
where id=object_id(@t)
) a
exec(@sql)