1

I am trying to query XML data in a table using a SQL parameter containing the search criteria and I am getting unexpected results.

As an example, consider the following T-SQL code:

DECLARE @Configuration AS TABLE
(
    [Data] XML NOT NULL
);

INSERT INTO Configuration ([Data]) VALUES '<Configuration><Colors><Color>RED</Color><Color>BLUE</Color></Colors></Configuration>');

DECLARE @Color AS NVARCHAR(MAX);

SET @Color = N'YELLOW';

SELECT COUNT(*) FROM @Configuration WHERE [Data].exist('/Configuration/Colors/Color/text() = sql:variable("@Color")') = 1;

I would expect the result of this query to return 0. In fact, this query returns 1. Even worse, it appears to return one regardless of what value I set @Color to.

What am I missing?

1 Answer 1

3

You have missing [ in your query

SELECT COUNT(*) FROM @Configuration WHERE [Data].exist('/Configuration/Colors/Color[text() = sql:variable("@Color")]') = 1;

XPath expressions are supposed to be enclosed between [ and ]. For more information on XPath and writing expressions, please refer this tutorial page.

Sign up to request clarification or add additional context in comments.

9 Comments

Any idea what the actual semantics are of the query in the OP? What is it actually evaluating the exist against?
@MartinSmith I believe he is trying to find if the given parameter value exists in the XML
That wasn't what I asked. I asked what the query is currently doing. As it doesn't raise any error. Is it just basically evaluating the existence of a Boolean result?
@MartinSmith Not sure what you are asking; Please fill-in additional details whatever I have misunderstood or incorrectly answered; I was only concerned to fix the issue he had
I am not sure what is being asked either (perhaps I left some detail off of my original question). The answer provided here is what I was looking for. As such, I have marked it as the accepted solution. Thank you for the help.
|

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.