SQL Server 2005 하위 선택 문제에서 Union을 사용하여 XML 경로 선택
-
20-09-2019 - |
문제
오히려 SQL Server "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>
그래서 (서브) 쿼리를 Union-Select로 변경했습니다.
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')
하지만 이제 오류가 발생합니다 "하위 쿼리가 존재하지 않을 때 선택 목록에 하나의 표현식 만 지정할 수 있습니다."
XML 경로 마녀의 하위 쿼리에 여러 레코드가 여러 요소로 발생할 수 있다는 것을 알고 있습니다. 그러나 나는 이것이 노동 조합으로 왜 그렇게 할 수 없는지 이해하지 못한다.
누군가 내 (서브) 쿼리의 2 개의 키 필드로 XML을 성취하는 방법을 올바른 방향으로 만들 수 있습니까?
당신을 매우 고맙습니다.
해결책
SubSelect의 문제점은 첫 번째 부분이 어떤 테이블도 전혀 언급하지 않는다는 것입니다. FROM-
절).
이 목록은 귀하가 요청한 출력을 제공합니다.
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