sql中實現split()功能


http://www.cnblogs.com/yangyy753/archive/2011/11/23/2260618.html

數據庫中,總是遇到一些字段內容,想根據某個標識截取一下字符串,可是都想不到好辦法,如果能有一個像ASP.NET里面的Split方法,那該多好,多方便啊!

為什么不可以?我們自己寫一個函數不就可以解決了嗎?好吧,說干就干,自己來寫個SplitString函數!

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)

結果,截個圖來看一下:

里面還有個自增的[Id]字段哦,在某些情況下有可能會用上的,例如根據Id來保存排序等等。

例如根據某表的ID保存排序:

 update a set a.[Order]=t.[Id]
        from [dbo].[] as a join [dbo].SplitString('1,2,3', ',', 1) as t on a.[Id]=t.[Value]

 


免責聲明!

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



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