我有两个单独的表TV和Receivers,我使用FOR XML PATH命令来构建XML。我的问题是我想将TV XML Build的输出与我的Receiver XML Build结合起来创建一个XML输出。
所以我会有类似的东西(这使我能够在FilterData Root中保持电视和接收器标签分开):
<FilterData>
<TVs>
<TV>
<Type>LCD</Type>
<Brand>Samsung</Brand>
</TV>
<TV>
<Type>LCD</Type>
<Brand>Panasonic</Brand>
</TV>
</TVs>
<Receivers>
<Receiver>
<Type>Surround 7.1</Type>
<Brand>Onkyo</Brand>
</Receiver>
<Receiver>
<Type>Surround 7.1</Type>
<Brand>Denon</Brand>
</Receiver>
</Receivers>
</FilterData>
问题在于,当我构建查询以输出此XML
时Select
Type
,Brand
From dbo.TVs
FOR XML PATH('TV'),ROOT('TVS') TYPE
和
Select
Type
,Brand
From dbo.Receivers
FOR XML PATH('Receiver'),ROOT('Receivers') TYPE
我不确定如何将它们组合成示例:
<FilterData>
<TVs>
<TV>
<Type>LCD</Type>
<Brand>Samsung</Brand>
</TV>
<TV>
<Type>LCD</Type>
<Brand>Panasonic</Brand>
</TV>
</TVs>
<Receivers>
<Receiver>
<Type>Surround 7.1</Type>
<Brand>Onkyo</Brand>
</Receiver>
<Receiver>
<Type>Surround 7.1</Type>
<Brand>Denon</Brand>
</Receiver>
</Receivers>
答案 0 :(得分:7)
使用:
SELECT (SELECT t.type, t.brand
FROM dbo.TVs t
FOR XML PATH('tv'), ROOT('tvs'), ELEMENTS, TYPE),
(SELECT r.type, r.brand
FROM dbo.Receivers r
FOR XML PATH('receiver'), ROOT('receivers'), ELEMENTS, TYPE)
FOR XML PATH('filterdata')
使用:
进行测试WITH tvs AS (
SELECT 'LCD' AS type, 'Samsung' AS brand
UNION ALL
SELECT 'LCD' AS type, 'Panasonic' AS brand),
receivers AS (
SELECT 'Surround 7.1' AS type, 'Onkyo' AS brand
UNION ALL
SELECT 'Surround 7.1', 'Denon')
SELECT (SELECT t.type, t.brand
FROM tvs t
FOR XML PATH('tv'), ROOT('tvs'), ELEMENTS, TYPE),
(SELECT r.type, r.brand
FROM receivers r
FOR XML PATH('receiver'), ROOT('receivers'), ELEMENTS, TYPE)
FOR XML PATH('filterdata')
答案 1 :(得分:2)
DECLARE @tvs TABLE
(
[Type] varchar(20) not null
, [Brand] varchar(50) not null
)
DECLARE @receivers TABLE
(
[Type] varchar(20) not null
, [Brand] varchar(50) not null
)
INSERT INTO @tvs([Type], [Brand]) Values('LCD', 'Samsung'), ('LCD', 'Panasonic');
INSERT INTO @receivers([Type], [Brand]) Values('Surround 7.1', 'Onkyo'), ('Surround 7.1', 'Dennon');
SELECT
(
SELECT
[Type]
, [Brand]
FROM
@tvs
FOR XML PATH('TV'),ROOT('TVS'), TYPE
)
,
(
SELECT
[Type]
, [Brand]
FROM
@receivers
FOR XML PATH('Receiver'),ROOT('Receivers'), TYPE
)
FOR XML PATH('FilterData');