0

I am trying to make a query like this dynamic using variables in SQL Server.

Original Query (returns results)

select
*
from items
where [key] in ('material', 'type') 
and value in ('nylon/latex', 'general purpose')

New Query (returns empty set)

declare @keys nvarchar(max) = 'material, type'
declare @values nvarchar(max) = 'nylon/latex, general purpose'

select
*
from items
where [key] in (@keys) 
and value in (@values)

How can I pass CSV data into these in clauses dynamically?

Matthew
  • 1,461
  • 3
  • 23
  • 49
  • Check out https://stackoverflow.com/questions/23089579/how-to-separate-split-string-with-comma-in-sql-server-stored-procedure Also, if you have a fairly recent version of SQL Server (compatibility level at least 130) then you can use STRING_SPLIT function: `...where [key] in SELECT value FROM STRING_SPLIT(@keys)` – Skippy Nov 08 '19 at 22:16
  • If your keys and values are all completely different then you could also try `...where @keys like '%' + [key] + '%'` – Skippy Nov 08 '19 at 22:20

0 Answers0