简体   繁体   English

如何在SQL Server中的xml列中查询xml值

[英]How to query xml value inside a xml column in SQL server

I have something like following code inside [XMLValue] column of a table called "AlgorithmLog": 我喜欢在名为“AlgorithmLog”的表的[XMLValue]列中跟随代码:

<?xml version="1.0" encoding="utf-8"?>
<AdapterInfo xmlns:i="http://www.w3.org/2001/XMLSchema-instance"     
            xmlns:d1p1="http://schemas.datacontract.org/2004/07/Adapters.Adapter.CloudTrader"    
            xmlns="http://schemas.datacontract.org/2004/07/Adapters.Adapter"  
            i:type="d1p1:AlgorithmStatusReport">
    <SequenceNumber>0</SequenceNumber>
    <TrackingGuid i:nil="true" />
    <d1p1:Broker>Default</d1p1:Broker>
    ...
       <d1p1:XMLValue>&lt;?xml version="1.0"?&gt;&lt;int xmlns="http://schemas.microsoft.com/2003/10/Serialization/"&gt;1900&lt;/int&gt;</d1p1:XMLValue>
</AdapterInfo>

and I want to get the value "1900" inside the node <d1p1:XMLValue> 我想在节点<d1p1:XMLValue>获取值“1900”

So here is my query: 所以这是我的查询:

WITH XMLNAMESPACES('http://schemas.datacontract.org/2004/07/Adapters.Adapter' AS x, 
                   'http://schemas.datacontract.org/2004/07/Adapters.Adapter.CloudTrader' As p,
                   'http://schemas.microsoft.com/2003/10/Serialization/'as w)
   SELECT  
       XMLValue.query('(/x:AdapterInfo/p:XMLValue/w:int)[1]')AS [XMLVaule]
   FROM AlgorithmLog 

But it returns nothing. 但它什么也没有回报。

Could anyone tell me where I did wrong or how I can do it? 谁能告诉我哪里做错了或我怎么做?

Thank you. 谢谢。

Since you have "encoded" XML inside another XML node, and you cannot automatically cast to the XML datatype using the .value() XQuery method, it all gets a bit involved - but this seems to work for me: 由于您已在另一个XML节点内“编码”了XML,并且无法使用.value() XQuery方法自动转换为XML数据类型,因此所有内容都有所涉及 - 但这似乎对我有用:

;WITH XMLNAMESPACES('http://schemas.datacontract.org/2004/07/Adapters.Adapter' AS x, 
                    'http://schemas.datacontract.org/2004/07/Adapters.Adapter.CloudTrader' As p,
                    'http://schemas.microsoft.com/2003/10/Serialization/'as w)
   SELECT  
       CAST(XmlContent.value('(/x:AdapterInfo/p:XMLValue)[1]', 'varchar(2000)') AS XML).value('(w:int)[1]', 'int') AS [XMLValue]
   FROM AlgorithmLog
   WHERE .......  -- use whatever condition makes sense for you here

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

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