SQL Server 2005中的XML路径与子选择问题联合选择
-
20-09-2019 - |
题
我而经历了SQL服务器“选择XML路径”查询,但现在我遇到了一个奇怪的问题。
下面的查询工作正常:
select
(
select
'Keyfield1' as "@Name",
t1.Keyfield1 as "Value"
from MyTable t1
where
t1.KeyField1= t2.KeyField1 and
t1.KeyField2= t2.KeyField2
for xml path('Field'),type, elements
) as 'Key'
from MyTable t2
for XML path('Path') , elements XSINIL, root('Root')
这将导致(对于虚设数据集)在这个XML:
<Root>
<Path>
<Key Name="KeyField1">
<Value>DummyValue1</Value>
</Key>
</Path>
</Root>
在我发言我需要的第二关键字段太这(一个更大的部分)的结果:
<Root>
<Path>
<Key Name="KeyField1">
<Value>DummyValue1</Value>
</Key>
<Key Name="KeyField2">
<Value>DummyValue2</Value>
</Key>
</Path>
</Root>
,所以我改变我的(亚)查询与工会选择为:
select
(
select
'Keyfield1' as "@Name",
t1.Keyfield1 as "Value"
union all
select
'Keyfield2' as "@Name",
t1.Keyfield2 as "Value"
from MyTable t1
where
t1.KeyField1= t2.KeyField1 and
t1.KeyField2= t2.KeyField2
for xml path('Field'),type, elements
) as 'Key'
from MyTable t2
for XML path('Path') , elements XSINIL, root('Root')
但现在我得到错误的“只有一个表达式可以在选择列表中指定当子查询不与EXISTS引入的。” 的
我知道它有可能具有与用于在多个元素的XML路径女巫结果的子查询的多个记录。但我不明白为什么这不能与工会进行。
有人可以把我在正确的方向如何accomplisch与2个KeyFields中的XML在我的(子)查询?
感谢名单大家。
解决方案
与子选择的问题是,所述第一部分完全没有(无FROM-
clause)参照的任何表。
此房源给我你的要求的输出:
declare @mytable table (
keyfield1 nvarchar(20),
keyfield2 nvarchar(20)
)
insert into @mytable values ('Dummyvalue1', 'Dummyvalue2')
select * from @mytable
select
(
select
'Keyfield1' as "@Name",
t1.Keyfield1 as "Value"
from @mytable t1
where
t1.KeyField1= t2.KeyField1 and
t1.KeyField2= t2.KeyField2
for xml path('Field'),type, elements
) as 'Key'
from @mytable t2
for XML path('Path') , elements XSINIL, root('Root')
select
(
select * from (
select
'Keyfield1' as "@Name",
t1.Keyfield1 as "Value"
from @MyTable t1
where
t1.KeyField1= t2.KeyField1
union all
select
'Keyfield2' as "@Name",
t3.Keyfield2 as "Value"
from @MyTable t3
where
t3.KeyField2= t2.KeyField2) a
for xml path('Field'),type, elements
) as 'Key'
from @MyTable t2
for XML path('Path') , elements XSINIL, root('Root')
其他提示
下面是一个简单的例子,但这并得到你所需要的?
select
(
select
'Keyfield1' as "@Name",
'Blah' as "Value"
for xml path('Key'),type, elements
),
(
select
'Keyfield2' as "@Name",
'Blah' as "Value"
for xml path('Key'),type, elements
)
for XML path('Path') , elements XSINIL, root('Root')
不隶属于 StackOverflow