Split function equivalent in T-SQL?

后端 未结 15 1815
深忆病人
深忆病人 2020-11-21 07:23

I’m looking to split \'1,2,3,4,5,6,7,8,9,10,11,12,13,14,15...\' (comma delimited) into a table or table variable.

Does anyone have a function that returns each one

15条回答
  •  北海茫月
    2020-11-21 08:03

    This is most like .NET, for those of you who are familiar with that function:

    CREATE FUNCTION dbo.[String.Split]
    (
        @Text VARCHAR(MAX),
        @Delimiter VARCHAR(100),
        @Index INT
    )
    RETURNS VARCHAR(MAX)
    AS BEGIN
        DECLARE @A TABLE (ID INT IDENTITY, V VARCHAR(MAX));
        DECLARE @R VARCHAR(MAX);
        WITH CTE AS
        (
        SELECT 0 A, 1 B
        UNION ALL
        SELECT B, CONVERT(INT,CHARINDEX(@Delimiter, @Text, B) + LEN(@Delimiter))
        FROM CTE
        WHERE B > A
        )
        INSERT @A(V)
        SELECT SUBSTRING(@Text,A,CASE WHEN B > LEN(@Delimiter) THEN B-A-LEN(@Delimiter) ELSE LEN(@Text) - A + 1 END) VALUE      
        FROM CTE WHERE A >0
    
        SELECT      @R
        =           V
        FROM        @A
        WHERE       ID = @Index + 1
        RETURN      @R
    END
    
    SELECT dbo.[String.Split]('121,2,3,0',',',1) -- gives '2'
    

提交回复
热议问题