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

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

    This one uses PATINDEX to match ids from a table to a non-digit delimited integer list.

    -- Given a string @myList containing character delimited integers 
    -- (supports any non digit delimiter)
    DECLARE @myList VARCHAR(MAX) = '1,2,3,4,42'
    
    SELECT * FROM [MyTable]
        WHERE 
            -- When the Id is at the leftmost position 
            -- (nothing to its left and anything to its right after a non digit char) 
            PATINDEX(CAST([Id] AS VARCHAR)+'[^0-9]%', @myList)>0 
            OR
            -- When the Id is at the rightmost position
            -- (anything to its left before a non digit char and nothing to its right) 
            PATINDEX('%[^0-9]'+CAST([Id] AS VARCHAR), @myList)>0
            OR
            -- When the Id is between two delimiters 
            -- (anything to its left and right after two non digit chars)
            PATINDEX('%[^0-9]'+CAST([Id] AS VARCHAR)+'[^0-9]%', @myList)>0
            OR
            -- When the Id is equal to the list
            -- (if there is only one Id in the list)
            CAST([Id] AS VARCHAR)=@myList
    

    Notes:

    • when casting as varchar and not specifying byte size in parentheses the default length is 30
    • % (wildcard) will match any string of zero or more characters
    • ^ (wildcard) not to match
    • [^0-9] will match any non digit character
    • PATINDEX is an SQL standard function that returns the position of a pattern in a string

提交回复
热议问题