支持text字段处理的仅有:
下面的函数和语句可以与 ntext、text 或 image 数据一起使用。
函数 语句
datalength readtext
patindex set textsize
substring updatetext
textptr writetext
textvalid
1:替换
–创建数据测试环境
create table #tb(aa text)
insert into #tb select abc123abc123,asd
–定义替换的字符串
declare @s_str varchar(8000),@d_str varchar(8000)
select @s_str=123 –要替换的字符串
,@d_str=000 –替换成的字符串
–字符串替换处理
declare @p varbinary(16),@postion int,@rplen int
select @p=textptr(aa),@rplen=len(@s_str),@postion=charindex(@s_str,aa)-1 from #tb
while @postion>0
begin
updatetext #tb.aa @p @postion @rplen @d_str
select @postion=charindex(@s_str,aa)-1 from #tb
end
–显示结果
select * from #tb
–删除数据测试环境
drop table #tb
/****************全部替换************************/
declare @ptrval binary(16)
select @ptrval = textptr(aa) from #tb where aa like %数据2%
if @ptrval is not null — 一定要加上此句,否则若找不到数据下一句就会报错
updatetext #tb.aa @ptrval 0 null 数据3
/****************在字段尾添加**********************************/
–定义添加的的字符串
declare @s_str varchar(8000)
select @s_str=*c –要添加的字符串
–字符串添加处理
declare @p varbinary(16),@postion int,@rplen int
select @p=textptr(detail) from test where id=001
updatetext test.detail @p null null @s_str
总结:
1:text字段类型不能直接用replace函数来替换,必须用updatetext
2:字段比较不能用 where 字段 = ‘某数据’,可以用like来代替
3:updatetext时,若@ptrval值为空会出错,需注意。
