从SQL列中提取XML值

时间:2016-06-26 07:11:29

标签: sql sql-server

我是SQL查询的新手。我有一个内容类似于XML的列。

XML的一个例子如下:

<AlertParameters>
    <AlertParameter1>Database drive C: is below critical threshold on space for last 00:15:00.
Note: Data may be stale. To get current data, run: Get-ServerHealth -Identity 'Serverxx' -HealthSet 'MailboxSpace'
Note: Subsequent detected alerts are suppressed until the health set is healthy again.
    </AlertParameter1>
    <AlertParameter2>http://technet.microsoft.com/en-us/library/ms.exch.scom.MailboxSpace(EXCHG.150).aspx?v=15.0.847.32
    </AlertParameter2>
    <AlertParameter3>MailboxSpace health set unhealthy (StorageLogicalDriveSpaceMonitor/C:) - Exchange Server Alert: Database drive C: is below critical threshold on space for last 00:15:00.
    </AlertParameter3>
</AlertParameters>

我需要提取AlertParameter3标记之间的值。我已经尝试了值函数,但无法使其工作。我收到一个错误,即:

  

找不到列“AlertParams”或用户定义的函数或聚合“AlertParams.Value”,或者名称不明确。

我看到的所有示例都涉及指定XML命名空间或声明XML文本。如果我需要对列进行选择并且没有命名空间,我该如何从列中提取此数据?

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

您可以使用xQuery提取所需内容。

DECLARE @test TABLE (
    String xml
)

INSERT INTO @test VALUES 
('<AlertParameters>
<AlertParameter1>Database drive C: is below critical threshold on space for last 00:15:00.
Note: Data may be stale. To get current data, run: Get-ServerHealth -Identity ''Serverxx'' -HealthSet ''MailboxSpace''
Note: Subsequent detected alerts are suppressed until the health set is healthy again.
</AlertParameter1>
<AlertParameter2>http://technet.microsoft.com/en-us/library/ms.exch.scom.MailboxSpace(EXCHG.150).aspx?v=15.0.847.32
</AlertParameter2>
<AlertParameter3>MailboxSpace health set unhealthy (StorageLogicalDriveSpaceMonitor/C:) - Exchange Server Alert: Database drive C: is below critical threshold on space for last 00:15:00.
</AlertParameter3>
</AlertParameters>')


SELECT String.value('(/AlertParameters/AlertParameter3)[1]','nvarchar(max)')
FROM @test

输出:

MailboxSpace health set unhealthy (StorageLogicalDriveSpaceMonitor/C:) - Exchange Server Alert: Database drive C: is below critical threshold on space for last 00:15:00. 

如果列具有nvarchar数据类型,则使用CAST:

SELECT CAST(String as xml).value('(/AlertParameters/AlertParameter3)[1]','nvarchar(max)')
FROM @test