Using tuples in SQL “IN” clause

前端 未结 8 1112
刺人心
刺人心 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: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 = '';
      
    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).

提交回复
热议问题