Split function by comma in SQL Server 2008

后端 未结 6 918
-上瘾入骨i
-上瘾入骨i 2020-12-06 21:58

I know that this question has been asked many times but could not find what I needed.

I have this column \"Order\" which contains data in the following format.

6条回答
  •  北海茫月
    2020-12-06 22:40

    I've change the function name so it won't overlapped in what the Split() function really does.

    Here is the code:

    CREATE FUNCTION dbo.GetColumnValue(
    @String varchar(8000),
    @Delimiter char(1),
    @Column int = 1
    )
    returns varchar(8000)
    as     
    begin
    
    declare @idx int     
    declare @slice varchar(8000)     
    
    select @idx = 1     
        if len(@String)<1 or @String is null  return null
    
    declare @ColCnt int
        set @ColCnt = 1
    
    while (@idx != 0)
    begin     
        set @idx = charindex(@Delimiter,@String)     
        if @idx!=0 begin
            if (@ColCnt = @Column) return left(@String,@idx - 1)        
    
            set @ColCnt = @ColCnt + 1
    
        end
    
        set @String = right(@String,len(@String) - @idx)     
        if len(@String) = 0 break
    end 
    return @String  
    end
    

    And here is the usage:

    select dbo.GetColumnValue('Col1,Field2,VAlue3', ',', 3)
    

提交回复
热议问题