2013-08-08

TSQL - Function to transform a given comma-separated string value into a table with one row per element

Execution example:

getTableFromCSV('asdf,qwer,poiu');


Funcion's code:

ALTER function [dbo].[getTableFromCSV]
(
       @csv VARCHAR(MAX)
)
RETURNS
       @tbl TABLE( val VARCHAR(255) )
AS
BEGIN

       DECLARE @sTemp VARCHAR(255)
       WHILE LEN(@csv) > 0
       BEGIN
              SET @sTemp = LEFT(@csv, ISNULL(NULLIF(CHARINDEX(',', @csv) - 1, -1), LEN(@csv)))
              SET @csv = SUBSTRING(@csv,ISNULL(NULLIF(CHARINDEX(',', @csv), 0), LEN(@csv)) + 1, LEN(@csv))
              INSERT INTO @tbl VALUES (LTRIM(RTRIM(@sTemp)))
       END
       -- kill the nulls/ empty strings
       DELETE FROM @tbl WHERE val IS NULL OR val = '' 
RETURN
END
;


No comments:

Post a Comment