简体   繁体   English

如何查询SQL Server中的XML列中的数据

[英]How to query data in XML column in SQL Server

I have data like this in an xml column: 我在xml列中有这样的数据:

<product>
   <productID>1</productID>
   <productname>tea</productname>
</product>
<product>
   <productID>2</productID>
   <productname>coffee</productname>
</product>

I want to change the value of productname to green tea where productID = 2 . 我想将productname的值更改为productID = 2 绿茶

I am using: 我在用:

UPDATE [dbo].ProductDocs
SET ProductDoc.modify('replace value of (/Product/ProductName)[2] with "NewName"')

But here it will always change the value in second product. 但在这里它总会改变第二个产品的价值。 Please tell me how to query with productID . 请告诉我如何使用productID进行查询。

Use predicate expression to filter product element by productID value like so : 使用谓词表达式按productID值过滤product元素,如下所示:

UPDATE [dbo].ProductDocs
SET ProductDoc.modify('
    replace value of (/product[productID=2]/productname/text())[1] with "NewName"
')

Also notice that, as mentioned in the other answer, XML and XPath/XQuery are case-sensitive. 另请注意,如其他答案中所述,XML和XPath / XQuery区分大小写。

First thing first, XML is case-sensitive and so are the XQuery expressions. 首先, XML是区分大小写的, XQuery表达式也是如此。

Now you could do this. 现在你可以做到这一点。

UPDATE [dbo].ProductDocs
SET ProductDoc.modify('replace value of (/product[productID=2]/productname/text())[1] with "GreenTea"')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM