但是目前有許多現存系統仍然存在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('%'[email protected]+'%',[info]) from t where [email protected]
    while @position>0
    begin
        set @[email protected]
        updatetext t.[info] @ptr @position @len @strdsc
      select @position=patindex('%'[email protected]+'%',[info]) from t where [email protected]
    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 [email protected]
    select @strtmp = replace(@strtmp,@strsrc,@strdsc)
    update t set [info] = @strtmp where [email protected]
    fetch next from replace_cursor into @id
end
close replace_cursor
deallocate replace_cursor
go
這樣,無論info字段改成char,nchar,text都好,一樣均可通用
 
新聞熱點
疑難解答