Skip to content
Advertisement

How to convert comma separated variable values to row in SQL Server 2012?

I have a variable in my stored procedure `@param varchar’, the parameter value will be like ‘333,445,443,222’ or ‘555’

I need to store into as row in the #Employee table, Code column.

Expected output:

#Employee temp table:

Code
----
333
445
443
222

Advertisement

Answer

It will work with any SQL server version. User define table function

CREATE FUNCTION dbo.SplitString
(
  @Value     nvarchar(max),
  @Delim    nvarchar(5)
)
RETURNS TABLE
AS
  RETURN ( SELECT [Value] FROM 
  ( 
    SELECT [Value] = LTRIM(RTRIM(SUBSTRING(@Value, [Number],
      CHARINDEX(@Delim, @Value + @Delim, [Number]) - [Number])))
    FROM (SELECT Number = ROW_NUMBER() OVER (ORDER BY name)
      FROM sys.all_columns) AS x WHERE Number <= LEN(@Value)
      AND SUBSTRING(@Delim + @Value, [Number], DATALENGTH(@Delim)/2) = @Delim
    ) AS y
  );

and then it can be used

DECLARE @param varchar(1000)
SET @param = '333,445,443,222'

SELECT value AS Code FROM dbo.SplitString(@param, ',');

Demo: http://sqlfiddle.com/#!18/9eecb/89486

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement