我需要一个SQL查询来从XML元素中获取最后一个属性值。我有XML,如下所示。我需要获取名称值,即“当前状态合同”#39;来自legalNames / Name Path。对此有任何帮助表示赞赏..
<legalNames id="l5922F64208E14D97BEE4C2E94B670146" deleted="0">
<operatingNames id="o370FA0A9EAE54290B132211A1EB28D8D" deleted="0">
<Name>CSR Contracting</Name>
</operatingNames>
<Name prior="" id="N45BF84B89B4F4DB987C07EF568E585D9">Current State Contracting</Name>
</legalNames>
答案 0 :(得分:0)
尝试这样(SQL-Server语法):
DECLARE @xml XML=
'<legalNames id="l5922F64208E14D97BEE4C2E94B670146" deleted="0">
<operatingNames id="o370FA0A9EAE54290B132211A1EB28D8D" deleted="0">
<Name>CSR Contracting</Name>
</operatingNames>
<Name prior="" id="N45BF84B89B4F4DB987C07EF568E585D9">Current State Contracting</Name>
</legalNames>';
select @xml.value('(/legalNames/Name)[1]','nvarchar(max)')
答案 1 :(得分:0)
抱歉延迟回复,我实际上找到了解决方案。 使用(。)而不是列将解决这样的问题(&#39;(。)[1]&#39;,&#39; varchar(500)&#39;)。下面是我从LegalNames / Name路径获取所有值的确切代码。
SELECT HistoryID,
x.r.value('(@id)[1]', 'varchar(500)') AS NameID,
x.r.value('(@prior)[1]', 'varchar(500)') AS Name_prior,
x.r.value('(.)[1]', 'varchar(500)') AS Name
From
(select HistoryID,XMLData
FROM [Compass Source_Test].dbo.Temp_History_table_july11) s
CROSS apply s.XMLData.nodes('legalNames/Name') as x(r)