sqlserver 中ntext字段的批量替换(updatetext的用法)

一、问题描述:

1。在sql server 中,ntext/text/image 字段不允许应用replace函数替换内容;

2。通过convert字段转换,可以把ntext字段转换为varchar(8000),然后用relpace函数替换,不过,此方法,对于字段长度大于8000的ntext字段无效。


二、问题解决
整理通用存储过程,代码如下:


复制代码 代码如下:

create procedure [dbo].[proc_updatentextfield]

@targettable nvarchar(1000), –目标表名

@targetfield nvarchar(1000), –目标字段名

@pkfield nvarchar(1000), –该表主键字段名

@otxt nvarchar(1000),         –需要替换的字符串

@ntxt nvarchar(1000)         –替换后的字符串

as

begin

declare @sqlstr nvarchar(4000)

set @sqlstr = ‘ declare @txtlen int ‘

set @sqlstr = @sqlstr + ‘ set @txtlen = len(”’ + @otxt + ”’) ‘

set @sqlstr = @sqlstr + ‘ declare @pos int ‘

set @sqlstr = @sqlstr + ‘ set @pos = 0 ‘

set @sqlstr = @sqlstr + ‘declare curs cursor local fast_forward for select ‘

set @sqlstr = @sqlstr + @pkfield + ‘ , textptr(‘ + @targetfield +’) from ‘ + @targettable +’ where ‘ + @targetfield + ‘ like ”%’ + @otxt +’%”’

set @sqlstr = @sqlstr + ‘ declare @ptr binary(16) ‘

set @sqlstr = @sqlstr + ‘ declare @id char(32) ‘

set @sqlstr = @sqlstr + ‘ open curs ‘

set @sqlstr = @sqlstr + ‘ fetch next from curs into @id, @ptr ‘

set @sqlstr = @sqlstr + ‘ while @@fetch_status = 0 ‘

set @sqlstr = @sqlstr + ‘ begin ‘

set @sqlstr = @sqlstr + ‘ select @pos= patindex(”%’ + @otxt + ‘%”,productdesc) from producttemp where productid=@id ‘

set @sqlstr = @sqlstr + ‘ while @pos>0 ‘

set @sqlstr = @sqlstr + ‘ begin ‘

set @sqlstr = @sqlstr + ‘ set @pos=@pos-1 ‘

set @sqlstr = @sqlstr + ‘ updatetext ‘ + @targettable + ‘.’ +@targetfield + ‘ @ptr @pos @txtlen ”’ + @ntxt + ”’ ‘

set @sqlstr = @sqlstr + ‘ select @pos= patindex(”%’ + @otxt + ‘%”,productdesc) from producttemp where productid=@id ‘

set @sqlstr = @sqlstr + ‘ end ‘

set @sqlstr = @sqlstr + ‘ fetch next from curs into @id, @ptr ‘

set @sqlstr = @sqlstr + ‘ end ‘

set @sqlstr = @sqlstr + ‘ close curs ‘

set @sqlstr = @sqlstr + ‘ deallocate curs ‘

execute sp_executesql @sqlstr

end

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐