MSSQL批量替換Text字串

來源:互聯網
上載者:User
字串

但是目前有許多現存系統仍然存在text類型的欄位,因為種種原因已經不能修改資料庫結構。
但是我們可以在新寫的sql語句及預存程序中採用新的方法,以備將來mssql server拋棄專門針對text等類型的操作函數後修改程式的麻煩。
下面是一個簡單的替換例子,

針對text類型的字串替換:

設有表 T(id int not null,info text)
要求替換info中的'abc'為'123'
一般的預存程序會寫成:
drop procedure dbo.procedure_1
go
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
create procedure dbo.procedure_1
as
declare @ptr varbinary(16)
declare @ID int
declare @Position int,@len int
declare @strsrc char(3)
declare @strdsc char(3)
set @strtmp='abc'
set @strdsc='123'
set @len=3
declare replace_Cursor scroll Cursor
for
select textptr([info]),id from T
for read only
open replace_Cursor
fetch next from replace_Cursor into @ptr,@ID
while @@fetch_status=0
begin
    select @Position=patindex('%'+@strsrc+'%',[info]) from T where id=@ID
    while @Position>0
    begin
        set @Position=@Position-1
        updatetext T.[info] @ptr @Position @len @strdsc
      select @Position=patindex('%'+@strsrc+'%',[info]) from T where id=@ID
    end
    fetch next from replace_Cursor into @ptr,@ID
end
close replace_Cursor
deallocate replace_Cursor
go

其中用到了text專用的函數 updatetext

現在我們改寫成
drop procedure dbo.procedure_1
go

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

create procedure dbo.procedure_1
as

declare @ID int
declare @strtmp varchar(max)
declare @strsrc char(3),@strdsc char(3)
set @strsrc = 'abc'
set @strdsc = '123'
declare replace_Cursor scroll Cursor
for
select id from testtable
--for read only
open replace_Cursor
fetch next from replace_Cursor into @ID
while @@fetch_status=0
begin
    select @strtmp = [info] from testtable where id=@ID
    select @strtmp = Replace(@strtmp,@strsrc,@strdsc)
    update T set [info] = @strtmp where id=@ID
    fetch next from replace_Cursor into @ID
end
close replace_Cursor
deallocate replace_Cursor
go

這樣,無論info欄位改成char,nchar,text都好,一樣均可通用


 



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.