• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
内蒙古峰回路转armyfeng
博客园    首页    新随笔    联系   管理    订阅  订阅

MSSQL批量替换Text字符串

但是目前有许多现存系统仍然存在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都好,一样均可通用

posted @ 2006-08-07 20:53  老冯  阅读(994)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3