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

后端 未结 14 1929
心在旅途
心在旅途 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 04:56
    DECLARE @StatusList varchar(MAX);
    SET @StatusList='1,2,3,4';
    DECLARE @Status SYS_INTEGERS;
    INSERT INTO  @Status 
    SELECT Value 
    FROM dbo.SYS_SPLITTOINTEGERS_FN(@StatusList, ',');
    SELECT Value From @Status;
    
    0 讨论(0)
  • 2020-11-28 04:59

    Starting with SQL2017 you can use STRING_SPLIT and do this:

    declare @myList nvarchar(MAX)
    set @myList = '1,2,3,4'
    select * from myTable where myColumn in (select value from STRING_SPLIT(@myList,','))
    
    0 讨论(0)
  • 2020-11-28 05:01
    DECLARE @myList TABLE (Id BIGINT) INSERT INTO @myList(Id) VALUES (1),(2),(3),(4);
    select * from myTable where myColumn in(select Id from @myList)
    

    Please note that for long list or production systems it's not recommended to use this way as it may be much more slower than simple INoperator like someColumnName in (1,2,3,4) (tested using 8000+ items list)

    0 讨论(0)
  • 2020-11-28 05:03

    slight improvement on @LukeH, there is no need to repeat the "INSERT INTO": and @realPT's answer - no need to have the SELECT:

    DECLARE @MyList TABLE (Value INT) 
    INSERT INTO @MyList VALUES (1),(2),(3),(4)
    
    SELECT * FROM MyTable
    WHERE MyColumn IN (SELECT Value FROM @MyList)
    
    0 讨论(0)
  • 2020-11-28 05:03

    As no one mentioned it before, starting from Sql Server 2016 you can also use json arrays and OPENJSON (Transact-SQL):

    declare @filter nvarchar(max) = '[1,2]'
    
    select *
    from dbo.Test as t
    where
        exists (select * from openjson(@filter) as tt where tt.[value] = t.id)
    

    You can test it in sql fiddle demo

    You can also cover more complicated cases with json easier - see Search list of values and range in SQL using WHERE IN clause with SQL variable?

    0 讨论(0)
  • 2020-11-28 05:04

    No, there is no such type. But there are some choices:

    • Dynamically generated queries (sp_executesql)
    • Temporary tables
    • Table-type variables (closest thing that there is to a list)
    • Create an XML string and then convert it to a table with the XML functions (really awkward and roundabout, unless you have an XML to start with)

    None of these are really elegant, but that's the best there is.

    0 讨论(0)
提交回复
热议问题