My SQL code is fairly simple. I'm trying to select some data from a database like this:
SELECT * FROM DBTable
WHERE id IN (1,2,5,7,10)
I want to know how to declare the list before the select (in a variable, list, array, or something) and inside the select only use the variable name, something like this:
VAR myList = "(1,2,5,7,10)"
SELECT * FROM DBTable
WHERE id IN myList
That is not possible with a normal query since the
in
clause needs separate values and not a single value containing a comma separated list. One solution would be a dynamic queryI've always found it easier to invert the test against the list in situations like this. For instance...
This means that there is no complicated mish-mash required for the values that you are looking for.
As an example, if our list was
('1,2,3')
, then we add a comma to the start and end of our list like so:',' + @mysearchlist + ','
.We also do the same for the field value we're looking for and add wildcards:
'%,' + CAST(field3 AS VARCHAR) + ',%'
(notice the%
and the,
characters).Finally we test the two using the
LIKE
operator:',' + @mysearchlist + ',' LIKE '%,' + CAST(field3 AS VARCHAR) + ',%'
.Alternative to @Peter Monks.
If the number in the 'in' statement is small and fixed.
You can convert the list of passed values into a table valued parameter and then select against this list
In this example the string passed in '1,2,5,7,10' is split by the commas and each value is added as a new row within the
@tbl
table variable. This can then be selected against using standard SQL.If you intend to reuse this functionality you could go further and convert this into a function.
If you want input comma separated string as input & apply in in query in that then you can make Function like:
You can use it like :
Alternatively if you don't have comma-separated string as input, You can try
Table variable
ORTableType
OrTemp table
like: INSERT using LIST into Stored ProcedureYou could declare a variable as a temporary table like this:
Which means you can use the
insert
statement to populate it with values:Then your
select
statement can use either thein
statement:Or you could join to the temporary table like this:
And if you do something like this a lot then you could consider defining a user-defined table type so you could then declare your variable like this: