sql数据库批量替换整个数据库语句

发布时间:2020-09-27编辑:脚本学堂
有关sql server中批量替换整个数据库的一段sql语句,用到了游标,批量替换所有表中的数据信息,需要的朋友参考下。

批量替换语句,如下:
 

复制代码 代码示例:

declare cur cursor FOR
SELECT name,id FROM sysobjects WHERE xtype=U
 
open cur
fetch next FROM cur INTO @tableName,@tbID
 
while @@fetch_status=0
begin
declare cur1 cursor FOR
    --xtype in (231,167,239,175,99) 为char,varchar,nchar,nvarchar,ntext类型
    SELECT name FROM syscolumns WHERE xtype IN (231,167,239,175,99) AND id=@tbID
open cur1
fetch next FROM cur1 INTO @columnName
while @@fetch_status=0
begin
  SET @sql=update [ + @tableName + ] set [+ @columnName +]= replace(cast([+@columnName+] as varchar(8000)),+@Str1+,+@Str2+) where [+@columnName+] like %+@Str1+%
  --update tablename set fieldA=replace(cast(fieldA as varchar(8000)) ,aa,bb)这样的语句。
  exec sp_executesql @sql    
  SET @iRow=@@rowcount
  SET @iResult=@iResult+@iRow
  IF @iRow>0
  begin
print 表:+@tableName+,列:+@columnName+被更新+convert(varchar(10),@iRow)+条记录;
  end    
  fetch next FROM cur1 INTO @columnName
end
close cur1
deallocate cur1
 
fetch next FROM cur INTO @tableName,@tbID
end
print 数据库共有+convert(varchar(10),@iResult)+条记录被更新!!!

--关闭游标
close cur
deallocate cur
SET nocount off