3

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.

2 Answers 2

3

I think you must use xmlCol.exist instead of query.

SELECT
    *
FROM
    @tmp
WHERE
    (typeId = 1) AND
    (xmlCol.exist('/search/groups/g[@id=25]') = 1)
Sign up to request clarification or add additional context in comments.

1 Comment

That returns an error: XQuery [@tmp.xmlCol.exist()]: No more tokens expected at the end of the XQuery expression. Found ')'.
2

Use xmlcol.exist. Something like this.

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

 DECLARE @id int = 25

SELECT * FROM @tmp
WHERE typeId = 1 
    AND xmlCol.exist('search/groups/g[@id= sql:variable("@id")]') = 1

1 Comment

Lovely example with variable. Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.