日期:2014-05-18  浏览次数:20358 次

ntext类型字段中的字符串全表替换(在线等待!)
数据库数据表 TB 有字段 Content
我想把TB中字段Content中的所有字符串'http://192.168.1.110/'替换成'web'

例如
http://192.168.1.110/掌骨额http://192.168.1.110/阳升的地方http://192.168.1.110/永点http://192.168.1.110/
转换后
web掌骨额web阳升的地方web永点web

注意:1、是全表替换
  2、是ntext类型字段
  3、要替换的字符串可能出现在字段的任何位置
  4、请注明关键地方的注视



------解决方案--------------------
LZ:你Content应该不止含有 http://192.168.1.110/ 这个吧
如果你只想更新含有http://192.168.1.110/ 这个的话,Try[注意:下面语句只能更新<8000字符内的Content]
SQL code

Declare @T Table(id int,Content ntext)
Insert @T Select 1,'http://192.168.1.110/掌骨额http://192.168.1.110/阳升的地方http://192.168.1.110/永点http://192.168.1.110/ '
Union All Select 2,'李四http://192.168.1.110/张三http://192.168.1.110/阳升的地方'
--更新
Update @T Set Content=Replace(Cast(Content As Varchar(8000)),'http://192.168.1.110/','web')
--查询更新后的结果
Select * From @T

---结果
/*
id          Content   
----------- ---------------------------------
1           web掌骨额web阳升的地方web永点web 
2           李四web张三web阳升的地方

(所影响的行数为 2 行)
*/

------解决方案--------------------
在sql2005下面不在建议使用TEXT\NTEXT\IMAGE数据类型,请使用NVARCHAR(MAX)代替
------解决方案--------------------
SQL code

DECLARE @insert_offset int,@delete_length int
DECLARE @newstr varchar(50)

set @delete_length = len('http://192.168.1.110/')
set @newstr = 'web'

select @insert_offset = patindex('%http://192.168.1.110/%',str)-1 from a where id=1

DECLARE @ptrval binary(16)
SELECT @ptrval = TEXTPTR(str) FROM a where id=1
UPDATETEXT a.str @ptrval @insert_offset @delete_length @newstr

------解决方案--------------------
用bcp将数据导出,用word替换,再用bcp导入