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
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.
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:
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>';
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).