zoukankan      html  css  js  c++  java
  • SQL里面用自定义Split()

    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO

    CREATE function [dbo].[SplitString]
    (
        @Input nvarchar(max),
        @Separator nvarchar(max)=',',
        @RemoveEmptyEntries bit=1
    )
    returns @TABLE table
    (
        [Id] int identity(1,1),
        [Value] nvarchar(max)
    )
    as
    begin
        declare @Index int, @Entry nvarchar(max)
        set @Index = charindex(@Separator,@Input)

        while (@Index>0)
        begin
            set @Entry=ltrim(rtrim(substring(@Input, 1, @Index-1)))
           
            if (@RemoveEmptyEntries=0) or (@RemoveEmptyEntries=1 and @Entry<>'')
                begin
                    insert into @TABLE([Value]) Values(@Entry)
                end

            set @Input = substring(@Input, @Index+datalength(@Separator)/2, len(@Input))
            set @Index = charindex(@Separator, @Input)
        end
       
        set @Entry=ltrim(rtrim(@Input))
        if (@RemoveEmptyEntries=0) or (@RemoveEmptyEntries=1 and @Entry<>'')
            begin
                insert into @TABLE([Value]) Values(@Entry)
            end

        return
    end

    函数、表都建好了,下面调用测试一下吧:

    	declare @str1 varchar(max), @str2 varchar(max), @str3 varchar(max)
    
    set @str1 = '1,2,3'
    set @str2 = '1###2###3'
    set @str3 = '1###2###3###'
    
    select [Value] from [dbo].[SplitString](@str1, ',', 1)
    select [Value] from [dbo].[SplitString](@str2, '###', 1)
    select [Value] from [dbo].[SplitString](@str3, '###', 0)
    

    结果,截个图来看一下:

    \

  • 相关阅读:
    【转】Mybatis常见面试题总结
    【转】深入分析@Transactional的用法
    刷抖音极速版,大家一起来赚钱
    公司喜欢什么样的员工呢?
    边学习新技术边工作的重要性
    聊聊IT行业加班的问题
    软件工程师怎样减轻工作过程中遇到的压力
    如何找兼职工作
    常用的网址导航
    几家主要的配送(跑腿)服务提供商
  • 原文地址:https://www.cnblogs.com/yuhanzhong/p/2920559.html
Copyright © 2011-2022 走看看