对同一数据库下的多个数据表的同一字段进行处理举例
例如
多个数据表中都含有csign字段,需要替换空格为空,‘’
1 查询含有该字段的数据表名称
select sc.name,so.name from syscolumns sc left join
sysobjects so on sc.id=so.id
where sc.name='csign' and so.type='u'
或
select so.name from sysobjects so where so.id in (select id from syscolumns
where name='csign' )
and so.type='u'
2 实现替换‘ ’替换为‘’
声明列名、表名和定义游标
declare @colname as nvarchar(100),@tablename as nvarchar(100),@sql as nvarchar(1000)
declare @cur as cursor
set @colname='csign'
为游标赋值
set @cur=CURSOR for (select so.name from syscolumns sc left join
sysobjects so on sc.id=so.id
where sc.name='csign' and so.type='u')
--默认为全局游标,
声明局部游标也可以:set @cur=cursor global/local for这里没有必要
打开游标
open @cur
获取值到临时变量中
fetch @cur into @tablename
循环替换
while @@FETCH_STATUS=0 --获取成功
begin
set @sql='update ' + @tablename +' set ' +@colname +' =replace('+
@colname +','' '','''')'
print @sql
exec(@sql)
fetch next from @cur into @tablename
end
关闭游标
close @cur
释放游标
deallocate @cur