Objective
I want to run SQL queries with IN statement into an Excel file and using dynamic parameters.
The queries
First, it can be:
SELECT feature1
FROM table
WHERE feature2 IN (?)
or
SELECT feature1
FROM table
WHERE feature2 IN ?
The second one has systematic error whatever the parameters
Syntax error or access violation
So I focused on the first one.
The Parameters
I am having problems to specify the list of parameters (Data -> Request and connection -> Connections -> Definition -> Parameters) :
- 'a','b','c' -> returns Nothing
- "a","b","c" -> returns Nothing
- "'a','b','c'" -> returns Nothing
- 'a' -> returns Nothing
- a -> returns Something
- a,b,c -> returns Nothing
Last but not least, when it's hard encoded, this returns Something:
SELECT feature1
FROM table
WHERE feature2 IN ('a', 'b', 'c')
Questions
What's happening ? How can I specify dynamically multiple parameters ? Is there a way to visualise this built query to check what's wrong? Or any techniques to avoid the problem ?
Preferably, without VBA
Using Excel 2019 and Microsoft SQL Server 2012 (No STRING_SPLIT
, OPENJSON
)
EDIT
Based on the answers and on this post, I tried with this sql query to avoid using STRING_SPLIT
and OPENJSON
:
SELECT feature1
FROM table
WHERE feature2 IN (
SELECT Split.a.value('.', 'NVARCHAR(MAX)') DATA
FROM (
SELECT CAST('<X>'+REPLACE( ? , ',', '</X><X>')+'</X>' AS XML) AS String
) AS A
CROSS APPLY String.nodes('/X') AS Split(a)
);
However, it doesn't understand the parameter via Excel, while it works when it's hard coded in the query.