SQL Server procedure declare a list

后端 未结 6 671
粉色の甜心
粉色の甜心 2020-12-24 05:28

My SQL code is fairly simple. I\'m trying to select some data from a database like this:

SELECT * FROM DBTable
WHERE id IN (1,2,5,7,10)

I w

6条回答
  •  鱼传尺愫
    2020-12-24 05:53

    I've always found it easier to invert the test against the list in situations like this. For instance...

    SELECT 
        field0, field1, field2 
    FROM 
        my_table 
    WHERE 
        ',' + @mysearchlist + ',' LIKE '%,' + CAST(field3 AS VARCHAR) + ',%' 
    

    This means that there is no complicated mish-mash required for the values that you are looking for.

    As an example, if our list was ('1,2,3'), then we add a comma to the start and end of our list like so: ',' + @mysearchlist + ','.

    We also do the same for the field value we're looking for and add wildcards: '%,' + CAST(field3 AS VARCHAR) + ',%' (notice the % and the , characters).

    Finally we test the two using the LIKE operator: ',' + @mysearchlist + ',' LIKE '%,' + CAST(field3 AS VARCHAR) + ',%'.

提交回复
热议问题