一个ntext字段,要对该字段内的指定字符串替换操作,但是用一条语句:update PE_Article set content = replace(cast(content as nvarchar(200000)),'[href=''uploadfile]','[href=''../oldweb/uploadfile]'),报错:nvarchar(200000)最大不允许超过8000,有什么办法?
...全文
21264打赏收藏
sql replace处理ntext问题
一个ntext字段,要对该字段内的指定字符串替换操作,但是用一条语句:update PE_Article set content = replace(cast(content as nvarchar(200000)),'[href=''uploadfile]','[href=''../oldweb/uploadfile]'),报错:nvarchar(200000)最大不允许超过8000,有什么办法?
--设置每次应该截取的数据的长度,防止REPLACE后数据溢出
@step=CASE WHEN LEN(@r_str)>LEN(@s_str)
THEN 4000/LEN(@r_str)*LEN(@s_str)
ELSE 4000 END
--替换处理的开始位置
SELECT @start=PATINDEX('%'+@s_str+'%',col),
@p=TEXTPTR(col),
@s=SUBSTRING(col,@start,@step),
@len=LEN(@s),
@last_repl=0
FROM tb
WHERE PATINDEX('%'+@s_str+'%',col)>0
AND TEXTVALID('tb.col',TEXTPTR(col))=1
WHILE @len>=@s_len
BEGIN
--得到最后一个被替换数据的位置
WHILE CHARINDEX(@s_str,@s,@last_repl)>0
SET @last_repl=@s_len
+CHARINDEX(@s_str,@s,@last_repl)
--如果需要,更新数据,同时判断下一个取数位置的偏移量
IF @last_repl=0
SET @last_repl=@s_len
ELSE
BEGIN
SELECT @last_repl=CASE
WHEN @len<@last_repl THEN 1
WHEN @len-@last_repl>=@s_len THEN @s_len
ELSE @len-@last_repl+2 END,
@s=REPLACE(@s,@s_str,@r_str),
@pos=@start-1
UPDATETEXT TB.col @p @pos @len @s
END
--获取下一个要处理的数据
SELECT @start=@start+LEN(@s)-@last_repl+1,
@s=SUBSTRING(col,@start,@step),
@len=LEN(@s),
@last_repl=0
FROM tb
END
GO
--显示处理结果
SELECT datalength(col),* FROM tb
DROP TABLE tb
exec sp_dboption 'hnimdb','select into/bulkcopy','true'
go
declare @Point varbinary(16),@Point2 varbinary(16),@var varchar(8000),@var2 varchar(8000)
declare @yxID int
select @yxID=min(yxID) from mysql.hneam.dbo.tbyxtlrz where jjman2 is null and reportdate>'2006-12-05'
select @yxID
select @Point = textptr(yxjs),@Point2=textptr(jdsx) from tbYXjzztlrz where num=@yxID+94
--select @Point,@Point2
select @var=yxjs,@var2=jdsx from mysql.hneam.dbo.tbyxtlrz where yxid=@yxID
if @var is null set @var=''
if @var2 is null set @var2=''
--select @var,@var2
writetext tbyxjzztlrz.yxjs @Point @var
writetext tbyxjzztlrz.jdsx @Point2 @var2
go
exec sp_dboption 'hnimdb','select into/bulkcopy','false'
go
--drop table aatt
create table aatt(id int ,atext Ntext)
insert into aatt select 1,N'[href=''uploadfile]test text tttttttttttgbgs fdgdfgdfg [href=''uploadfile] '
insert into aatt select 2,N'gdfhfghgfhdfhfghfghfgh......'
insert into aatt select 3,N'controlled[href=''uploadfile], into[href=''uploadfile] .....'
declare @aa BINARY(16)
declare @i int
declare @id int
declare RepaceText cursor
for
select id,PATINDEX('%''uploadfile%', atext) from aatt where PATINDEX('%''uploadfile%', atext)>0
open RepaceText
fetch next from RepaceText into @id,@i
while @@fetch_status=0
begin
--print @id
while @i>=0
begin
SELECT @aa = TEXTPTR(atext),
@i = PATINDEX('%''uploadfile%', atext) - 1
FROM aatt
WHERE id = @id
--print @i
if @i>=0
begin
UPDATETEXT aatt.atext
@aa
@i --插入的位置
1 --删除的字符数
WITH LOG
'../oldweb/uploadfile' --要新插入的文本
end
else
begin
break
end
end
fetch next from RepaceText into @id,@i
end
close RepaceText
deallocate RepaceText