I'm having a table with one XML column. I'd like to filter out the rows where a specific attribute in the XML match a string, essentially doing a WHERE or HAVING.
The table looks something like this
| id | xml |
And the XML something similar to
<xml>
<info name="Foo">
<data .../>
</info>
<xml>
I want to get all ids where the @name attribute matched a value.
I have been able to do the following:
SELECT id, xml.query('data(/xml/info/@name)') as Value
FROM Table1
WHERE CAST(xml.query('data(/xml/info/@name)') as varchar(1024)) = @match
But it's incredibly slow.
There must be a better way of filtering on the output of the query.
XQuery in the SQL Server helps to query and extract data from XML documents. XQuery gives different approaches to get information from the XML document and the equivalent can be used on applying a data filter or where clause on XML elements as well.
You can optionally retrieve formal results of a SQL query as XML by specifying the FOR XML clause in the query. The FOR XML clause can be used in top-level queries and in subqueries. The top-level FOR XML clause can be used only in the SELECT statement.
Navigate through your XML Document in the Messages tab and right-click the element/attribute's value that you want to filter. Next, click the Add Data Filter action.
Found it. Instead of using query() I should be using exist().
My query would then be
SELECT id, xml.query('data(/xml/info/@name)') as Value
FROM Table1
WHERE xml.exist('/xml/info/[@name=sql:variable("@match")]') = 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With