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

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

    If you want to do this without using a second table, you can do a LIKE comparison with a CAST:

    DECLARE @myList varchar(15)
    SET @myList = ',1,2,3,4,'
    
    SELECT *
    FROM myTable
    WHERE @myList LIKE '%,' + CAST(myColumn AS varchar(15)) + ',%'
    

    If the field you're comparing is already a string then you won't need to CAST.

    Surrounding both the column match and each unique value in commas will ensure an exact match. Otherwise, a value of 1 would be found in a list containing ',4,2,15,'

提交回复
热议问题