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

前端 未结 7 1713
走了就别回头了
走了就别回头了 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:24

    Here's a trick that doesn't need a function or XML.

    Basically the string gets transformed into a single insert statement for a temporary table.

    The temp table can then be used for further processing.

    IF OBJECT_ID('tempdb..#tmpNum') IS NOT NULL
          DROP TABLE #tmpNum;
    
    CREATE TABLE #tmpNum (num int);
    
    DECLARE @TEXT varchar(max) = '1,17,25,44,46,67,88';
    
    DECLARE @InsertStatement varchar(max);
    SET  @InsertStatement = 'insert into #tmpNum (num) values ('+REPLACE(@TEXT,',','),(')+');';
    EXEC (@InsertStatement);
    
    -- use the temp table 
    SELECT * 
    FROM YourTable t
    WHERE t.id IN (SELECT DISTINCT num FROM #tmpNum);
    

    This method is usable for up to 1000 values.
    Because 1000 is the max limit of a row value expression.

    Also, as Stuart Ainsworth pointed out.
    Since this method uses Dynamic Sql, be wary of code injection and don't use it for strings based on user input.

    Side-note

    Starting from MS Sql Server 2016, one could simply use the STRING_SPLIT function.

    DECLARE @TEXT varchar(max);
    SET @TEXT = '1,17,25,44,46,67,88';
    
    SELECT t.* 
    FROM YourTable t
    JOIN (SELECT DISTINCT CAST(value AS INT) num FROM STRING_SPLIT(@TEXT, ',')) nums
      ON t.id = nums.num;
    

提交回复
热议问题