3 つの一見同一の XML nodes() クエリですが、最初のクエリは列の最初の行で異なる結果を返します: Location1、Location2、Location3
なぜ違うのでしょうか?
前もって感謝します。
declare @xml xml
set @xml =
'<root>
<Location1 LocationID="10">
<step1>apple</step1>
<step2>banana</step2>
</Location1>
<Location2 LocationID="20">
<step1>carrot</step1>
<step2>donut</step2>
</Location2>
<Location3 LocationID="30">
<step1>egg</step1>
<step2>fry</step2>
</Location3>
</root>'
declare @SQL nvarchar(max) = ''
declare @Col nvarchar(max) = ', N.value(''[COLNAME][1]'', ''varchar(100)'') as [COLNAME]'
select @SQL = @SQL + replace(@Col, '[COLNAME]', N.value('local-name(.)', 'sysname'))
from @XML.nodes('//*') as T(N)
set @SQL = 'select '+stuff(@SQL, 1, 2, '')+' from @XML.nodes(''//*'') as T(N)'
exec sp_executesql @SQL, N'@XML xml', @XML
declare @sql2 nvarchar(max) = ''
set @sql2 =
'select
n.value(''root[1]'',''varchar(100)'') as root,
n.value(''location1[1]'',''varchar(100)'') as location1,
n.value(''step1[1]'',''varchar(100)'') as step1,
n.value(''step2[1]'',''varchar(100)'') as step2,
n.value(''location2[1]'',''varchar(100)'') as location2,
n.value(''step1[1]'',''varchar(100)'') as step1,
n.value(''step2[1]'',''varchar(100)'') as step2,
n.value(''location3[1]'',''varchar(100)'') as location3,
n.value(''step1[1]'',''varchar(100)'') as step1,
n.value(''step2[1]'',''varchar(100)'') as step2
from @xml.nodes(''//*'') as t(n)'
exec sp_executesql @SQL2, N'@XML xml', @XML
select
n.value('root[1]','varchar(100)') as root,
n.value('location1[1]','varchar(100)') as location1,
n.value('step1[1]','varchar(100)') as step1,
n.value('step2[1]','varchar(100)') as step2,
n.value('location2[1]','varchar(100)') as location2,
n.value('step1[1]','varchar(100)') as step1,
n.value('step2[1]','varchar(100)') as step2,
n.value('location3[1]','varchar(100)') as location3,
n.value('step1[1]','varchar(100)') as step1,
n.value('step2[1]','varchar(100)') as step2
from @xml.nodes('//*') as t(n)
PS: わかりました。詳細を書かずにこれを投稿することはできません. . このようなもの(うまくいけば、フォーマットが残ることを願って、画像をアップロードできませんでした):
root Location1 LocationID Step1 Step2 Location2 Location3
Location1 LocationID 10
Step1 apple
Step2 banana
Location2 20 LocationID
carrot Step1
donut Step2
Location3 30 LocationID
egg Step1
fry Step2
なんらかの理由で、これは SQL にとって難しい注文ですが、上記のクエリの違いの理由についてはまだ興味があります。