How to convert comma separated NVARCHAR to table records in SQL Server 2005?

前端 未结 7 1629
走了就别回头了
走了就别回头了 2020-11-27 06:18

I have a list of ids separated by comma like:

 1,17,25,44,46,67,88

I want to convert them to a table records ( into a temporary table ) lik

7条回答
  •  隐瞒了意图╮
    2020-11-27 06:30

    Possible duplicate of separate comma separated values and store in table in sql server.

    Please try a precise one from Comma-Delimited Value to Table:

    CREATE FUNCTION [dbo].[ufn_CSVToTable] ( @StringInput VARCHAR(8000), @Delimiter nvarchar(1))
    RETURNS @OutputTable TABLE ( [String] VARCHAR(10) )
    AS
    BEGIN
    
        DECLARE @String    VARCHAR(10)
    
        WHILE LEN(@StringInput) > 0
        BEGIN
            SET @String      = LEFT(@StringInput, 
                                    ISNULL(NULLIF(CHARINDEX(@Delimiter, @StringInput) - 1, -1),
                                    LEN(@StringInput)))
            SET @StringInput = SUBSTRING(@StringInput,
                                         ISNULL(NULLIF(CHARINDEX(@Delimiter, @StringInput), 0),
                                         LEN(@StringInput)) + 1, LEN(@StringInput))
    
            INSERT INTO @OutputTable ( [String] )
            VALUES ( @String )
        END
    
        RETURN
    END
    GO
    

    Check the requirement in other way using XML:

    DECLARE @param NVARCHAR(MAX)
    SET @param = '1:0,2:1,3:1,4:0'
    
    SELECT 
         Split.a.value('.', 'VARCHAR(100)') AS CVS  
    FROM  
    (
        SELECT CAST ('' + REPLACE(@param, ',', '') + '' AS XML) AS CVS 
    ) AS A CROSS APPLY CVS.nodes ('/M') AS Split(a)
    

提交回复
热议问题