SQL查询属性值

时间:2017-07-31 17:19:20

标签: sql xml

我到处搜索,似乎在解决我的具体问题。我试图从我们的数据库中解析xml值。该表名为“Table.XMLfileData”,带有一列XMLData。该列的当前设置如下:

XML Data with Column Names

XML本身的设置都嵌套在属性中:

XML example

我希望能够从每个XML文件中提取任何数据。我在研究中发现的查询应该是这样的:

SELECT r.value('@first_name','varchar(60)')
   FROM TableName
CROSS APPLY columnname.nodes('Vehicle_Loan/Applicants/Applicant/first_name') AS  
 x(r)

但是我每次都会检索一个空值或空值。我是新来的,我做错了什么?

1 个答案:

答案 0 :(得分:1)

.value(...)需要单个节点才能使用 XPath区分大小写

SELECT r.value('(./@first_name)[1]','varchar(60)')
   FROM TableName
CROSS APPLY columnname.nodes('Vehicle_Loan/Applicants/Applicant') AS  
 x(r)

......工作实例......

DECLARE @xml XML = N'
<Vehicle_Loan>
    <Applicants>
        <Applicant first_name="Matt" />
        <Applicant first_name="Jim" />
    </Applicants>
</Vehicle_Loan>
';

SELECT r.value('(./@first_name)[1]','varchar(60)') AS [FirstName]
    FROM @xml.nodes('Vehicle_Loan/Applicants/Applicant') AS  x(r)

...输出......

FirstName
---------------
Matt
Jim