我的SQL Server表中有XML
类型列,该表中的XML文档如下所示:
<?xml version="1.0" encoding="utf-16"?>
<Product xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Key xmlns="urn:microsoft-dynamics-schemas/page/product">48;nyI9AAJ7/1AAVQBCADYAAAACe/8xAC4AMAAwAAAAAIfei8sC11;152438283530;</Key>
<Code xmlns="urn:microsoft-dynamics-schemas/page/product">PR238</Code>
<Version xmlns="urn:microsoft-dynamics-schemas/page/product">1.00</Version>
<ExternalRefNr xmlns="urn:microsoft-dynamics-schemas/page/product">46894046</ExternalRefNr>
<Name xmlns="urn:microsoft-dynamics-schemas/page/product">Nailgun XJ-3</Name>
</Product>
现在,在SQL Server(X)查询中,我想选择该产品的名称(Nailgun XJ-3),但无论我尝试什么,我总是得到一个空的结果。
我想它应该是简单的,就像下面的一行,但我错过了一些东西。也许这是对命名空间的处理,但我找不到合适的方法来做到这一点。
SELECT ProductDetailSourceXML.query('//Name') FROM Product
答案 0 :(得分:2)
是的,它是XML命名空间 - 因为它存在,你必须尊重它并妥善处理它!
试试这个:
DECLARE @tbl TABLE (ID INT NOT NULL, ProductsDetailXML XML)
INSERT INTO @tbl VALUES(1, N'<?xml version="1.0" encoding="utf-16"?>
<Product xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Key xmlns="urn:microsoft-dynamics-schemas/page/product">48;nyI9AAJ7/1AAVQBCADYAAAACe/8xAC4AMAAwAAAAAIfei8sC11;152438283530;</Key>
<Code xmlns="urn:microsoft-dynamics-schemas/page/product">PR238</Code>
<Version xmlns="urn:microsoft-dynamics-schemas/page/product">1.00</Version>
<ExternalRefNr xmlns="urn:microsoft-dynamics-schemas/page/product">46894046</ExternalRefNr>
<Name xmlns="urn:microsoft-dynamics-schemas/page/product">Nailgun XJ-3</Name>
</Product>')
-- define the XML namespace and a prefix to use in your XQuery
;WITH XMLNAMESPACES('urn:microsoft-dynamics-schemas/page/product' AS ns)
SELECT
ID,
-- use the XML namespace prefix where needed!
ProductName = XC.value('(ns:Name)[1]', 'varchar(50)')
FROM
@tbl
CROSS APPLY
ProductsDetailXML.nodes('/Product') AS XT(XC)
WHERE
ID = 1