Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL : Find if XML node exists

Assuming I have a table data as below:Sample Table

I want to Select all Value(XML Data) which contains the node Name="Hello World". How can I achieve it?

SQL Fiddle

set @f = @XML.exist('/ArrayOfFilterColumn/SelectColumn[(@Name) eq "Hello World"]');
select @f;

I am not sure how could I add it in my where condition, so I have put it in a fiddle.

like image 796
Gun.IO Avatar asked Mar 13 '15 06:03

Gun.IO


People also ask

How do I check if an XML tag exists in SQL?

The exist() method in the WHERE clause returns 1 (True) if the XML does not include any < Specifications > element. Note the use of the not() function (XQuery). The sql:column() function (XQuery) function is used to bring in the value from a non-XML column.

How do I query XML data?

XML data can be queried using an SQL fullselect or with the SQL/XML query functions of XMLQUERY and XMLTABLE. The XMLEXISTS predicate can also be used in SQL queries on XML data.

How do I filter XML data in SQL Server?

SQL Server provides the XQuery feature to querying XML data type or querying with the XML column with the XPATH. Using XQuery, users can Insert, Update and Delete with the XML nodes and node values in an XML column.


1 Answers

Skip the use of an XML variable and put the exist in the where clause when you query the table.

select F.Value
from XML_FILES as F
where F.Value.exist('/ArrayOfArrayOfSelectColumn/SelectColumn[@Name eq "Hello World"]') = 1

Your column is apparently text so you need to change that because text is deprecated and has been for quite some time.

ntext, text, and image (Transact-SQL)

ntext , text, and image data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.

In your case you should of course change to XML instead.

Until you fix that you can cast to XML in your query.

select F.Value
from XML_FILES as F
where cast(F.Value as xml).exist('/ArrayOfArrayOfSelectColumn/SelectColumn[@Name eq "Hello World"]') = 1
like image 110
Mikael Eriksson Avatar answered Sep 23 '22 09:09

Mikael Eriksson