如何从 t-sql 中的 xml 变量中获取节点名称和值 [英] How to get node name and values from an xml variable in t-sql

查看:29
本文介绍了如何从 t-sql 中的 xml 变量中获取节点名称和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 xml -

I have the following xml -

<Surveys xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ImmForm XML Schema NHS Direct.xsd"><Svy SurveyName="WeeklyFluSurveillance2012/13-NHSDirectWeek40w/e07/10/2012" OrgCode="NHS Direct"><TotCR>222.10</TotCR><PerCF>0.40</PerCF><PerCFunder1>0.20</PerCFunder1><PerCF1to4>0.30</PerCF1to4><PerCF5to14>0.50</PerCF5to14><PerCF15to44>0.40</PerCF15to44><PerCF45to64>0.20</PerCF45to64><PerCF65plus>3.60</PerCF65plus>
<PerCFNE>4.22</PerCFNE>
<PerCFNW>6.50</PerCFNW>
<PerCFYH>0.80</PerCFYH>
<PerCFEM>1.00</PerCFEM>
<PerCFWM>1.50</PerCFWM></Svy></Surveys>

我需要在具有 2 列(FieldName、FieldValue)的结果集中选择子节点名称及其值,例如 -

I need to select the child node name and its value in a resultset with 2 columns (FieldName, FieldValue) like -

TotCR   222.10
PerCF     0.40
...
PerCFWM   1.50

xml 中的节点会有所不同,并且可能并不总是相同.甚至这些值也可能是整数或文本.

The nodes in the xml will vary and may not always be same. Even the values may be integer or text.

你们能否建议如何在 SQL Server 2008 R2 中使用 OPENXML 执行此操作?

Can you guys please suggest how to do this using OPENXML in SQL Server 2008 R2?

推荐答案

您可以使用 local-name() 函数来获取 XML 节点的名称 - 尝试如下操作:

You can use the local-name() function to the get name of the XML node - try something like this:

DECLARE @input XML =  '...your xml here.....'

SELECT
    NodeName = C.value('local-name(.)', 'varchar(50)'),
    NodeValue = C.value('(.)[1]', 'varchar(50)') 
FROM @input.nodes('/Surveys/Svy/*') AS T(C)

这应该给你一个类似的输出:

This should give you an output something like:

这篇关于如何从 t-sql 中的 xml 变量中获取节点名称和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆