互联网解决方案咨询

梦想有多大路就会有多远:作一颗IT量子
  首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

数据库字符串内容批量更新

Posted on 2010-04-13 14:42  互联网粒子  阅读(235)  评论(0编辑  收藏  举报
数据库经常会遇到需要把一些内容白批量替换的问题,有时是因为存数据时没有编码,有时是因为有些不良的信息,要直接替换。
整理了下如何用SQL语句来替换:
替换指定列内容语句
update [t_test] set [detail] =  REPLACE([detail],'打到XXX','新字符串')
注意,这个语句是不能替换ntext的,除了ntext类型的字符类型是可以全部替换
如果要替换ntext类型字段是需要进行类型转换
update [t_test] set [detail] = replace(convert(varchar(4000), [detail]),'打到XXX','新字符串'') where id<4
写一小段SQL来执行完成整个数据表的替换
 
declare @ptr varbinary(16)
declare @artId int
declare @Position int,@len int
set @len = datalength('XXXA')
declare wux_Cursor scroll Cursor
for
select textptr([detail]),id from t_test
for read only
open wux_Cursor
fetch next from wux_Cursor into @ptr,@artId
while @@fetch_status=0
begin
select @Position=patindex('%打到XXX%',[detail]) from t_test where id=@artId
while @Position>0
begin
set @Position=@Position-1
updatetext [t_test].[detail] @ptr @Position @len 'XXXA'
select @Position=patindex('%打到XXX%',detail) from t_test where id=@artId
end
fetch next from wux_Cursor into @ptr,@artId
end
close wux_cursor
deallocate wux_cursor
go