字符串按分隔符号段范围查询

--> 生成测试数据表:tb

If not object_id('[tb]') is null
    Drop table [tb]
Go
Create table [tb]([col] nvarchar(21))
Insert [tb]
Select N'餐饮集团/华东区管理处/中央厨房/营销部' union all
Select N'餐饮集团' union all
Select N'餐饮集团/华东区管理处' union all
Select N'餐饮集团/华东区管理处/营销部' union all
Select N'餐饮集团/华东区管理处/中央厨房/营销1部' union all
Select N'餐饮集团/华东区管理处/中央厨房/营销2部' union all
Select N'餐饮集团/华东区管理处/中央厨房/营销2部'
Go
--Select * from [tb]

-->SQL查询如下:
-->SQL查询如下:
If not object_id('[fn_str]') is null
    Drop function [fn_str]
Go
create function [dbo].[fn_str]
(
 @value nvarchar(200),  --要提取的源串, 如'餐饮集团/华东区管理处/中央厨房/营销1部
 @flag nvarchar(10) ,   --要查找的分隔符号, 如 '/'
 @flag_begin_pos int ,  --源串中分隔符号出现的次数,以该次数作为提取字串的起始
 @flag_end_pos int      --源串中分隔符号出现的次数,以该次数作为提取字串的结束
)
returns  nvarchar(200)
as
begin
    declare @rtv nvarchar(200);
    declare @pos1 int, @pos2 int, @num int, @pos int;
    set @pos = 0 ;
    set @pos1 = 0 ; --保存要返回的字串位于源串的起始位置
    set @pos2 = 0 ; --保存要返回的字串位于源串的结束位置
    set @num = 0 ;  --保存遍历过程中分隔符合一共出现了多少次

    if @value is null or @flag is null or @flag_begin_pos is null
  or @flag_end_pos is null or @flag_begin_pos >= @flag_end_pos
    begin
        return null;
    end
   
    while 1=1
    begin
  --mark1
        Set @pos = charindex(@flag,@value,@pos);--查找标识符(如'/')位置
       
        if @pos = 0   --如果没有找到标识符(如'/'),则退出循环
        begin
            break;
        end
        else        
        begin
            set @num = @num + 1;  --遍历次数+1
            if @num=@flag_begin_pos --如果遍历次数=输入的标识符(如'/')起始位置
            begin
                set @pos1=@pos + 1; --设置返回字符串的起始位置=获得mark1的值加1
            end
            else
            begin
                if @num = @flag_end_pos --继续循环,直到遍历次数=输入的标识符(如'/')截止位置
                begin
                    set @pos2 = @pos ; --设置返回字符串的截止位置=获得mark2的值
                    break;
                end
            end
            --mark2
            set @pos = @pos + 1;--继续循环,遍历次数递增
        end
    end
   
    if @num <> @flag_end_pos
    begin
        set @rtv = N'NULL' ; --没有在源串中找到合适的字串, 返回null
    end
    else
    begin
        set @rtv = SUBSTRING(@value,@pos1,@pos2-@pos1); --最终获得要取的字符串值
    end

return @rtv;
end
GO

select dbo.fn_str(col,'/',1,2) as col12,dbo.fn_str(col,'/',2,3) as col23 from tb

/*
col12         col23
华东区管理处 中央厨房
NULL         NULL
NULL         NULL
华东区管理处 NULL
华东区管理处 中央厨房
华东区管理处 中央厨房
华东区管理处 中央厨房
*/

http://topic.csdn.net/u/20090902/17/817E99CE-6CD6-417E-A613-BA0E7C636E65.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值