1

三个看似相同的 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:好的。它不会让我不写更多就发布这个,所以:最终,我试图让 SQL 将 XML 文件解析为一个表,其中节点、元素和属性作为列标题,其各自的值或子节点在它们下面列出. 像这样的东西(我无法上传图像,希望格式仍然存在):

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 来说是一个很高的要求,但我仍然对上述查询的差异感到好奇。

4

1 回答 1

0

原因是 xml 元素名称区分大小写。在第一个查询中,您有Location1, Location2, Location3, 在第二个location1, location2,location3

于 2013-09-07T10:18:21.360 回答