TSQL Variable With List of Values for IN Clause

前端 未结 4 1300
攒了一身酷
攒了一身酷 2021-01-04 19:27

I want to use a clause along the lines of \"CASE WHEN ... THEN 1 ELSE 0 END\" in a select statement. The tricky part is that I need it to work with \"value IN @List\".

4条回答
  •  无人及你
    2021-01-04 20:14

    You can use a variable in an IN clause, but not in the way you're trying to do. For instance, you could do this:

    declare @i int
    declare @j int
    
    select @i = 10, @j = 20
    
    select * from YourTable where SomeColumn IN (@i, @j)
    

    The key is that the variables cannot represent more than one value.

    To answer your question, use the inline select. As long as you don't reference an outer value in the query (which could change the results on a per-row basis), the engine will not repeatedly select the same data from the table.

提交回复
热议问题