Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>My solution would be to create a UDF that will parse the CSV data into a table variable. Then, in the SP, retrieve the CSV, pass it to the UDF, then run the query against the table variable.</p> <p>First, create a UDF to return a table from the CSV value (uses CHAR(13) to determine new lines, may need to be altered to work with your data):</p> <pre><code>CREATE FUNCTION [dbo].[fnParseCSV] (@InputString NVARCHAR(MAX), @Delimiter NCHAR(1) = ',') RETURNS @tbl TABLE (ID int, Val NVARCHAR(64)) AS BEGIN declare @singleLine nvarchar(max) declare @id int declare @val varchar(64) WHILE LEN(@InputString) &gt; 0 BEGIN IF CHARINDEX(char(13), @InputString) &gt; 0 BEGIN SELECT @singleLine = SUBSTRING(@InputString, 1, CHARINDEX(char(13), @InputString) - 1) IF CHARINDEX(@Delimiter, @singleline) &gt; 0 BEGIN SELECT @id = convert(int, SUBSTRING(@singleline, 1, CHARINDEX(@Delimiter, @singleline) - 1)) SELECT @val = RIGHT(@singleline, LEN(@singleline) - CHARINDEX(@Delimiter, @singleline) ) INSERT INTO @tbl (id, val) values (@id, @val) END SELECT @InputString = RIGHT(@InputString, LEN(@InputString) - CHARINDEX(char(13), @InputString) ) END ELSE BEGIN IF CHARINDEX(@Delimiter, @inputString) &gt; 0 BEGIN SELECT @id = convert(int, SUBSTRING(@inputString, 1, CHARINDEX(@Delimiter, @inputString) - 1)) SELECT @val = RIGHT(@inputString, LEN(@inputString) - CHARINDEX(@Delimiter, @inputString) ) INSERT INTO @tbl (id, val) values (@id, @val) END set @inputString = '' END END RETURN END </code></pre> <p>Then run the query against that output:</p> <pre><code>select * from dbo.fnParseCsv('123,val1' + char(13) + '456,val2' + CHAR(13) + '789,val3', ',') </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload