使用SQL查询XML数据

时间:2015-10-28 10:56:26

标签: sql sql-server xml database tsql

我有一个包含XML列的日志表。我研究了几个查询XML的例子,但它们并不符合我的需求。

Id   TimeStamp            Message    Properties
------------------------------------------------------------------------------
1    2015-10-27 08:45:38  Text       <properties><property key="time">23.10.2015 15:00:40</property><property key="interceptors">False</property></properties>
2    2015-10-27 09:21:09  Text       <properties><property key="Product">Azure</property><property key="Source">Azure Infrastructure</property></properties>
3    2015-10-27 16:51:32  Text       <properties><property key="Product">Azure</property><property key="Source">Azure Infrastructure</property><property key="Uptime">00:00:27.3874982</property></properties>
4    2015-10-28 11:03:25  Text       <properties><property key="Uptime">00:19:21.4729461</property></properties>

我想拥有所有节点值的结果集,其中属性节点具有“正常运行时间”键。结果集可能如下所示:

Id   Uptime
-----------------
3    00:00:27.3874982
4    00:19:21.4729461

2 个答案:

答案 0 :(得分:1)

下面是一个方法,它使用带有属性过滤器的xquery表达式和CTE来避免重复表达式:

WITH Uptimes AS (
    SELECT
          Id
        , Properties.value('(/properties/property[@key="Uptime"])[1]', 'time(7)') AS Uptime
    FROM dbo.test
    )
SELECT Id, Uptime
FROM Uptimes
WHERE Uptime IS NOT NULL;

答案 1 :(得分:1)

您可以使用以下sql

quick brown cat jumped over the lazy 
quick brown monkey jumped over the lazy