我需要按字母顺序排序属性名称,并且我创建了以下代码,但它保留了原样:
DECLARE @xml XML = N'<tt>
<cpost s="a" cena="0.0000" cpost_id="16385" flprt="1" moq="0"
valuta_id="2" nmatr_id="14117" norg_id="1791" />
</tt>'
SELECT
t.query('.')
FROM @xml.nodes('*/*') AS t(t)
ORDER BY t.value('local-name(.)','nvarchar(max)')
FOR XML PATH(''), TYPE, ROOT('tt')
我在哪里弄错了?
答案 0 :(得分:3)
不漂亮,但这是我思考的地方。
<强> dbFiddle 强>
示例强>
DECLARE @xml XML = N'
<tt>
<cpost s="a" cena="0.0000" cpost_id="16385" flprt="1" moq="0" valuta_id="2" nmatr_id="14117" norg_id="1791" />
</tt>'
Declare @S varchar(max) = ''
Select @S = @S + concat(Item,'="',Value,'" ')
From (
Select Top 1000
Item = attr.value('local-name(.)','varchar(100)')
,Value = attr.value('.','varchar(max)')
From @XML.nodes('/tt/cpost') as A(r)
Cross Apply A.r.nodes('./@*') AS B(attr)
Order By attr.value('local-name(.)','varchar(100)')
) A
Select convert(xml,'<tt><cpost '+@S+'/></tt>')
<强>返回强>
<tt>
<cpost cena="0.0000" cpost_id="16385" flprt="1" moq="0" nmatr_id="14117" norg_id="1791" s="a" valuta_id="2" />
</tt>
编辑 - 添加内联方法
DECLARE @xml XML = N'
<tt>
<cpost s="a" cena="0.0000" cpost_id="16385" flprt="1" moq="0" valuta_id="2" nmatr_id="14117" norg_id="1791" />
</tt>'
Select convert(xml,'<tt><cpost '+Stuff((Select ' ' +concat(Item,'="',Value,'" ')
From (
Select Top 1000
Item = attr.value('local-name(.)','varchar(100)')
,Value = attr.value('.','varchar(max)')
From @XML.nodes('/tt/cpost') as A(r)
Cross Apply A.r.nodes('./@*') AS B(attr)
Order By attr.value('local-name(.)','varchar(100)')
) A
For XML Path ('')),1,1,'') +'/></tt>')