[英]Filter an XML column in SQL Server
I have an xml type column productsXML
in product
table我在
product
表中有一个 xml 类型列productsXML
Create Table Product
(
ProductId Int
productsXML XML
)
Insert Into Product Values (1,'<products><productInfo><Item>Car</Item></productInfo><products>'),
(2,'<products><productInfo><Item>Train</Item></productInfo><products>'),
(3,'<products></products>')
ProductId productsXML
1 <products><productInfo><Item>Car</Item></productInfo><products>
2 <products><productInfo><Item>Train</Item></productInfo><products>
3 <products></products>
I want to find all the rows that have <products></products>
我想找到所有具有
<products></products>
的行
I tried this:我试过这个:
Select *
From products
Where productsxml.exist('/products')=1
This is giving me all the rows that have products tag and understandably so.这给了我所有带有产品标签的行,这是可以理解的。 Is there a way to filter only those rows that have
<products></products>
有没有办法只过滤那些有
<products></products>
的行
PLease try the following solution.请尝试以下解决方案。
It is checking that the root products element has no child elements.它正在检查根产品元素是否没有子元素。
SQL SQL
DECLARE @tbl TABLE (ProductId int primary key, productsXML XML);
INSERT INTO @tbl (ProductId, productsXML) VALUES
(1,'<products><productInfo><Item>Car</Item></productInfo></products>'),
(2,'<products><productInfo><Item>Train</Item></productInfo></products>'),
(3,'<products></products>');
SELECT *
FROM @tbl
Where productsxml.exist('/products[not(*)]')=1
Output Output
+-----------+--------------+
| ProductId | productsXML |
+-----------+--------------+
| 3 | <products /> |
+-----------+--------------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.