comparing a column to a list of values in t-sql

后端 未结 2 579
感动是毒
感动是毒 2020-12-02 00:27

I have a situation where I am displaying records on a page, and I need a way for the user to select a subset of those records to be displayed on another page. These records

2条回答
  •  Happy的楠姐
    2020-12-02 01:06

    You can use the solution Joel Spolsky recently gave for this problem.

    SELECT * FROM MyTable
    WHERE ',' + 'comma,separated,list,of,words' + ','
      LIKE '%,' + MyTable.word + ',%';
    

    That solution is clever but slow. The better solution is to split the comma-separated string, and construct a dynamic SQL query with the IN() predicate, adding a query parameter placeholder for each element in your list of values:

    SELECT * FROM MyTable
    WHERE word IN ( ?, ?, ?, ?, ?, ?, ?, ? );
    

    The number of placeholders is what you have to determine when you split your comma-separated string. Then pass one value from that list per parameter.

    If you have too many values in the list and making a long IN() predicate is unwieldy, then insert the values to a temporary table, and JOIN against your main table:

    CREATE TEMPORARY TABLE TempTableForSplitValues (word VARCHAR(20));
    
    ...split your comma-separated list and INSERT each value to a separate row...
    
    SELECT * FROM MyTable JOIN TempTableForSplitValues USING (word);
    

    Also see many other similar questions on SO, including:

    • Dynamic SQL Comma Delimited Value Query
    • Passing a varchar full of comma delimited values to a SQL Server IN function
    • Parameterized Queries with Like and In
    • Parameterizing a SQL IN clause?

提交回复
热议问题