declare a variable with multiple items like an in for a where clause?

Jonathan Brotto 420 Reputation points
2024-08-08T14:19:55.0666667+00:00

Is it possible to declare a variable with multiple items like an in for a where clause?

SQL Server | SQL Server Transact-SQL
Developer technologies | Transact-SQL
Developer technologies | Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
Community Center | Not monitored
SQL Server | Other
{count} votes

Answer accepted by question author
  1. Viorel 125.6K Reputation points
    2024-08-08T14:32:43.9566667+00:00

    For example:

    declare @values varchar(max) = '100,250,30,700'
    
    select *
    from MyTable
    where id in (select [value] from string_split(@values, ','))
    
    -- OR:
    
    select t.*
    from MyTable t
    inner join string_split(@values, ',') as v on v.value = t.id
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.