


MSSQL批量替換Text字符串
但是我們可以在新寫的sql語句及存儲過程中采用新的方法,以備將來mssql server拋棄專門針對text等類型的操作函數(shù)后修改程序的麻煩。
下面是一個簡單的替換例子,
針對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專用的函數(shù) updatetext
現(xiàn)在我們改寫成
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都好,一樣均可通用
關鍵字:MSSQL、字段、數(shù)據(jù)庫
新文章:
- CentOS7下圖形配置網(wǎng)絡的方法
- CentOS 7如何添加刪除用戶
- 如何解決centos7雙系統(tǒng)后丟失windows啟動項
- CentOS單網(wǎng)卡如何批量添加不同IP段
- CentOS下iconv命令的介紹
- Centos7 SSH密鑰登陸及密碼密鑰雙重驗證詳解
- CentOS 7.1添加刪除用戶的方法
- CentOS查找/掃描局域網(wǎng)打印機IP講解
- CentOS7使用hostapd實現(xiàn)無AP模式的詳解
- su命令不能切換root的解決方法
- 解決VMware下CentOS7網(wǎng)絡重啟出錯
- 解決Centos7雙系統(tǒng)后丟失windows啟動項
- CentOS下如何避免文件覆蓋
- CentOS7和CentOS6系統(tǒng)有什么不同呢
- Centos 6.6默認iptable規(guī)則詳解