How to split a comma-separated value to columns

后端 未结 30 4033
刺人心
刺人心 2020-11-21 04:38

I have a table like this

Value   String
-------------------
1       Cleo, Smith

I want to separate the comma delimited string into two colu

30条回答
  •  死守一世寂寞
    2020-11-21 05:03

    We can create a function as this

    CREATE Function [dbo].[fn_CSVToTable] 
    (
        @CSVList Varchar(max)
    )
    RETURNS @Table TABLE (ColumnData VARCHAR(100))
    AS
    BEGIN
        IF RIGHT(@CSVList, 1) <> ','
        SELECT @CSVList = @CSVList + ','
    
        DECLARE @Pos    BIGINT,
                @OldPos BIGINT
        SELECT  @Pos    = 1,
                @OldPos = 1
    
        WHILE   @Pos < LEN(@CSVList)
            BEGIN
                SELECT  @Pos = CHARINDEX(',', @CSVList, @OldPos)
                INSERT INTO @Table
                SELECT  LTRIM(RTRIM(SUBSTRING(@CSVList, @OldPos, @Pos - @OldPos))) Col001
    
                SELECT  @OldPos = @Pos + 1
            END
    
        RETURN
    END
    

    We can then seperate the CSV values into our respective columns using a SELECT statement

提交回复
热议问题