I need to include an XML query as part of the WHERE predicate in a SELECT statement.
I have this structure:
DECLARE @tmp TABLE (typeId int, xmlCol xml);
INSERT INTO @tmp
(typeId, xmlCol)
VALUES
(1, '<search><groups><g id="25" /><g id="26" /></groups></search>'),
(1, '<search><groups><g id="250" /><g id="9" /></groups></search>'),
(2, '<search><groups><g id="25" /><g id="12" /><g id="125" /></groups></search>');
SELECT * FROM @tmp;
But I need to pull out rows where typeId=1 AND where the XML data contains <g id="25" />. So in my example I'd only see the first row in the result set.
I'd prefer an XML query rather than casting to nvarchar and using LIKE, if possible. I tried this but just get a syntax error:
SELECT
*
FROM
@tmp
WHERE
(typeId = 1) AND
(xmlCol.query('/search/groups/g[@id=25])'))
An expression of non-boolean type specified in a context where a condition is expected, near ')'.
I've been searching for examples but cannot find XML queries being used in this manner.