How to split a comma-separated value to columns

后端 未结 30 4034
刺人心
刺人心 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 04:48

    I think following function will work for you:

    You have to create a function in SQL first. Like this

    CREATE FUNCTION [dbo].[fn_split](
    @str VARCHAR(MAX),
    @delimiter CHAR(1)
    )
    RETURNS @returnTable TABLE (idx INT PRIMARY KEY IDENTITY, item VARCHAR(8000))
    AS
    BEGIN
    DECLARE @pos INT
    SELECT @str = @str + @delimiter
    WHILE LEN(@str) > 0 
        BEGIN
            SELECT @pos = CHARINDEX(@delimiter,@str)
            IF @pos = 1
                INSERT @returnTable (item)
                    VALUES (NULL)
            ELSE
                INSERT @returnTable (item)
                    VALUES (SUBSTRING(@str, 1, @pos-1))
            SELECT @str = SUBSTRING(@str, @pos+1, LEN(@str)-@pos)       
        END
    RETURN
    END
    

    You can call this function, like this:

    select * from fn_split('1,24,5',',')
    

    Implementation:

    Declare @test TABLE (
    ID VARCHAR(200),
    Data VARCHAR(200)
    )
    
    insert into @test 
    (ID, Data)
    Values
    ('1','Cleo,Smith')
    
    
    insert into @test 
    (ID, Data)
    Values
    ('2','Paul,Grim')
    
    select ID,
    (select item from fn_split(Data,',') where idx in (1)) as Name ,
    (select item from fn_split(Data,',') where idx in (2)) as Surname
     from @test
    

    Result will like this:

提交回复
热议问题