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

后端 未结 14 2083
心在旅途
心在旅途 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: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?

提交回复
热议问题