如何在SQL SERVER 上使用循环替换

来源:互联网 发布:原宿风p图软件 编辑:程序博客网 时间:2024/05/29 15:14

--select right(@strReplace,-2)

/*
循环替换一个字符串
set @strReplace='市;区;公司' 要替换的字符,以分号分隔
set @strTest = '厦门市思明区xxx信息科技有限公司' 需要进行替换的原字符串
*/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].getArraryReplaceStr') and xtype='FN')
Drop function  getArraryReplaceStr
GO
create function getArraryReplaceStr(@strReplace varchar(1000),@strTest varchar(1000))
returns varchar(100)
as
begin

declare @start int,@end int,@len int,@strTmp varchar(1000)
set @start=0
set @len=len(@strReplace)
while(@len>0)
begin
        --select @start
        select @end=CHARINDEX(';',@strReplace)
        --select @end
        if @start=@end
    begin
                set @len=0
                select @strTest=replace(@strTest,@strReplace,'')
        end
        else
        begin
                set @len=@end-@start
                --select @len
                select @strTmp=substring(@strReplace,@start,@len)
                select @strReplace=replace(@strReplace,@strTmp+';','')
                --select @strReplace
                select @strTest=replace(@strTest,@strTmp,'')
                --set @start=@end
        end
end
return @strTest
end
go
declare @strReplace varchar(1000),@strTest varchar(1000),@strTmp varchar(1000)
set @strReplace='市;区;公司'
set @strTest = '厦门市思明区xxx信息科技有限公司'

select dbo.getArraryReplaceStr(@strReplace,@strTest)