通常情况下若对数据库中某张表的某个或者数个字段进行更新或者替换,可以对相应字段进行update操作。即
update tablename set columnname = repalce(columnname,'','')
当要对全表所有内容进行全局替换时,例如将所有的#替换为空时,在整张table中字段相当多的情况下,对字段逐条update会显得相当麻烦。此时可以通过调用information_shema数据库以及结合游标进行批量处理。
information_schema是数据库中的系统库,里面存放了系统的相关表,记录了所有表中字段、权限等信息。进入information_schema.colunms表中取出想要更新表的所有字段名,放入游标中,进行循环操作。
declare test_cursor cursor for
select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'tablename'
open test_cursor
declare @col varchar(100)
fetch next from test_cursor into @col
while @@FETCH_STATUS = 0
begin
exec('update tablename set ['+@col+'] = replace(['+@col+'],''#'','''')')
fetch next from test_cursor into @col
end
close test_cursor
deallocate test_cursor