Sql Server中使用特定字符分割字符串


在T-SQL中我們經常批量操作時都會對字符串進行拆分,可是SQL Server中卻沒有自帶Split函數,所以要自己來實現了。這里將字符串分割以table形式輸出
語法如下:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
    /*
    create by shuke.li 2020-9-15
    */
    create function [dbo].[SplitString]
    (
        @Input nvarchar(max), --input string to be separated
        @Separator nvarchar(max)=',', --a string that delimit the substrings in the input string
        @RemoveEmptyEntries bit=1 --the return value does not include array elements that contain an empty string
    )
    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

只要在新建查詢里執行上面的代碼,即完成了split函數的建立。
下面來測試這一函數的功能,測試所使用的的SQL腳本如下:

declare @str1 varchar(max)
set @str1 = 'CFER-3345-3323,CFER-0023-2299,CFER-0023-6677,CFER-0023-7678,CFER-4565-2299,CFER-0023-6678'

select * from [dbo].[SplitString](@str1, ',', 0)

結果顯示如下圖所示:

 

 最終使用方法和c#中的split函數是不是很相似!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM