Define variable to use with IN operator (T-SQL)

后端 未结 14 1928
心在旅途
心在旅途 2020-11-28 04:24

I have a Transact-SQL query that uses the IN operator. Something like this:

select * from myTable where myColumn in (1,2,3,4)

Is there a wa

相关标签:
14条回答
  • 2020-11-28 05:06
    DECLARE @mylist TABLE (Id int)
    INSERT INTO @mylist
    SELECT id FROM (VALUES (1),(2),(3),(4),(5)) AS tbl(id)
    
    SELECT * FROM Mytable WHERE theColumn IN (select id from @mylist)
    
    0 讨论(0)
  • 2020-11-28 05:08

    There are two ways to tackle dynamic csv lists for TSQL queries:

    1) Using an inner select

    SELECT * FROM myTable WHERE myColumn in (SELECT id FROM myIdTable WHERE id > 10)
    

    2) Using dynamically concatenated TSQL

    DECLARE @sql varchar(max)  
    declare @list varchar(256)  
    select @list = '1,2,3'  
    SELECT @sql = 'SELECT * FROM myTable WHERE myColumn in (' + @list + ')'
    
    exec sp_executeSQL @sql
    

    3) A possible third option is table variables. If you have SQl Server 2005 you can use a table variable. If your on Sql Server 2008 you can even pass whole table variables in as a parameter to stored procedures and use it in a join or as a subselect in the IN clause.

    DECLARE @list TABLE (Id INT)
    
    INSERT INTO @list(Id)
    SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4
    
    
    SELECT
        * 
    FROM 
        myTable
        JOIN @list l ON myTable.myColumn = l.Id
    
    SELECT
        * 
    FROM 
        myTable
    WHERE
        myColumn IN (SELECT Id FROM @list)
    
    0 讨论(0)
提交回复
热议问题