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

标签 sql sql-server xml tsql

我在名为“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>

我想在节点 <d1p1:XMLValue> 中获取值“1900”

所以这是我的查询:

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 

但它什么也没返回。

谁能告诉我哪里做错了或者我该怎么做?

谢谢。

最佳答案

因为您已经在另一个 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

关于sql - 如何在 SQL Server 中的 xml 列中查询 xml 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11318811/

相关文章:

sql-server - SQl Server 仍然收到 "Timeout expired. The timeout period elapsed"错误

sql - 有没有办法合并这两个简单的查询

xml - 创建不带命名空间的 XML 元素

c# - 如何将 XML 文件读取到 Dictionary<String,List<String>> 中,空字符串为 null 元素

c# - 选择其中列 1 = 1 且列 2 = MAX(列 2)

mysql - 如何编写 SQL 查询以在一个表中显示最新交易?

mysql - 更新包含 int 数字的字符串部分

mysql - 获取MySQL数据库中所有表的记录数

xml - 有海洋温度的 API 吗?

sql-server - 在 Windows Server Core 计算机上启用和配置 MS DTC