一、問題描述:
1。在Sql Server 中,ntext/text/image 欄位不允許應用replace函數替換內容;
2。通過convert欄位轉換,可以把ntext欄位轉換為varchar(8000),然後用Relpace函數替換,不過,此方法,對於欄位長度大於8000的ntext欄位無效。
二、問題解決
整理通用預存程序,代碼如下:
<br /> CREATE procedure [dbo].[Proc_UpdateNTextField]</p><p> @TargetTable nvarchar(1000), --目標表名<br /> @TargetField nvarchar(1000), --目標欄位名<br /> @PKField nvarchar(1000), --該表主鍵欄位名<br /> @otxt nvarchar(1000), --需要替換的字串<br /> @ntxt nvarchar(1000) --替換後的字串</p><p> as<br /> begin</p><p> declare @SqlStr nvarchar(4000)</p><p> set @SqlStr = ' declare @txtlen int '<br /> set @SqlStr = @SqlStr + ' set @txtlen = len(''' + @otxt + ''') '</p><p> set @SqlStr = @SqlStr + ' declare @pos int '<br /> set @SqlStr = @SqlStr + ' set @pos = 0 '</p><p> set @SqlStr = @SqlStr + 'declare curs cursor local fast_forward for select '<br /> set @SqlStr = @SqlStr + @PKField + ' , textptr(' + @TargetField +') from ' + @TargetTable +' where ' + @TargetField + ' like ''%' + @otxt +'%''' </p><p> set @SqlStr = @SqlStr + ' declare @ptr binary(16) '<br /> set @SqlStr = @SqlStr + ' declare @id char(32) ' </p><p> set @SqlStr = @SqlStr + ' open curs ' </p><p> set @SqlStr = @SqlStr + ' fetch next from curs into @id, @ptr ' </p><p> set @SqlStr = @SqlStr + ' while @@fetch_status = 0 '<br /> set @SqlStr = @SqlStr + ' begin '<br /> set @SqlStr = @SqlStr + ' select @pos= patindex(''%' + @otxt + '%'',ProductDesc) from ProductTemp where ProductID=@id '<br /> set @SqlStr = @SqlStr + ' while @pos>0 '<br /> set @SqlStr = @SqlStr + ' begin '</p><p> set @SqlStr = @SqlStr + ' set @pos=@pos-1 '<br /> set @SqlStr = @SqlStr + ' updatetext ' + @TargetTable + '.' +@TargetField + ' @ptr @pos @txtlen ''' + @ntxt + ''' '<br /> set @SqlStr = @SqlStr + ' select @pos= patindex(''%' + @otxt + '%'',ProductDesc) from ProductTemp where ProductID=@id '</p><p> set @SqlStr = @SqlStr + ' end '</p><p> set @SqlStr = @SqlStr + ' fetch next from curs into @id, @ptr ' </p><p> set @SqlStr = @SqlStr + ' end ' </p><p> set @SqlStr = @SqlStr + ' close curs '<br /> set @SqlStr = @SqlStr + ' deallocate curs '</p><p> EXECUTE sp_executesql @SqlStr</p><p> end