Using tuples in SQL “IN” clause

前端 未结 8 1093
刺人心
刺人心 2020-11-28 04:30

I have a table containing the fields group_id and group_type and I want to query the table for all the records having any tuple (group id, group type) from

相关标签:
8条回答
  • 2020-11-28 05:11

    Given a very minor tweak (replace double quotes with single and add the VALUES keyword), your proposed syntax is valid Standard SQL-92 syntax i.e.

    SELECT *
      FROM mytable
     WHERE (group_id, group_type) IN (
                                      VALUES ('1234-567', 2), 
                                             ('4321-765', 3), 
                                             ('1111-222', 5)
                                     );
    

    Sadly, MSFT have not added it to SQL Server and consider it an 'unplanned' feature.

    FWIW PostgreSQL and Sqlite are examples of SQL products that support this syntax.

    0 讨论(0)
  • 2020-11-28 05:14

    I had a similar problem but my tuple collection was dynamic - it was sent over to the SQL Server in a query parameter. I came up with the following solution:

    1. Pass a tuple as an XML:

      DECLARE @tuplesXml xml = '<tuples><tuple group-id="1234-567" group-type="2"/><tuple group-id="4321-765" group-type="3"/></tuples>';
      
    2. Inner join the table that you want to filter with the XML nodes:

      SELECT t.* FROM mytable t
      INNER JOIN @tuplesXml.nodes('/tuples/tuple') AS tuple(col)
      ON tuple.col.value('./@group-id', 'varchar(255)') = t.group_id
      AND tuple.col.value('./@group-type', 'integer') = t.group_type
      

    It seems to work fine in my situation which is a bit more complex than the one described in the question.

    Keep in mind that it is necessary to use t.* instead of * and the table returned from nodes method needs to be aliased (it's tuple(col) in this case).

    0 讨论(0)
提交回复
热议问题