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

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

    Try this code

     SELECT RTRIM(part) as part
        INTO Table_Name
            FROM dbo.splitstring(@Your_Comma_string,',')
    

    splitstring Function is as follows

    CREATE FUNCTION dbo.splitstring ( @stringToSplit VARCHAR(MAX) )
    RETURNS
     @returnList TABLE ([Name] [nvarchar] (500))
    AS
    BEGIN
    
     DECLARE @name NVARCHAR(255)
     DECLARE @pos INT
    
     WHILE CHARINDEX(',', @stringToSplit) > 0
     BEGIN
      SELECT @pos  = CHARINDEX(',', @stringToSplit)  
      SELECT @name = SUBSTRING(@stringToSplit, 1, @pos-1)
    
      INSERT INTO @returnList 
      SELECT @name
    
      SELECT @stringToSplit = SUBSTRING(@stringToSplit, @pos+1, LEN(@stringToSplit)-@pos)
     END
    
     INSERT INTO @returnList
     SELECT @stringToSplit
    
     RETURN
    END
    

提交回复
热议问题