祝您有個美好的一天!從不同的表中獲取XML
我有一個問題。無法得到如何在1個結果XML中合併2個表。
這裏是樣品
DECLARE @t1 table (ID int identity(1,1), SomeField varchar(50))
DECLARE @t2 table (ID int identity(1,1), SomeField varchar(50), AnotherField varchar(50))
INSERT INTO @t1 (SomeField) VALUES ('rec1'),('rec2'),('rec3'),('rec4')
INSERT INTO @t2 (SomeField,AnotherField) VALUES ('s106','here'),('s12','just'),('s13','sample')
SELECT * FROM @t1 AS FirstTable
SELECT * FROM @t2 AS AnotherTable
通緝的結果:
<Root>
<FirstTable ID="1" SomeField="rec1" />
<FirstTable ID="2" SomeField="rec2" />
<FirstTable ID="3" SomeField="rec3" />
<FirstTable ID="4" SomeField="rec4" />
<AnotherTable ID="1" SomeField="s106" AnotherField="here" />
<AnotherTable ID="2" SomeField="s12" AnotherField="just" />
<AnotherTable ID="3" SomeField="s13" AnotherField="sample" />
</Root>
dbfiddle
新評註(編輯)
通過John Cappelletti回答,但需要把這一切都內第三桌。
這裏是新代碼:
DECLARE @t1 table (ID int identity(1,1), tID int, SomeField varchar(50))
DECLARE @t2 table (ID int identity(1,1), tID int, SomeField varchar(50), AnotherField varchar(50))
DECLARE @t3 table (ID int identity(1,1), field1 varchar(50), field2 varchar(50))
INSERT INTO @t1 (tID,SomeField) VALUES (1,'rec1'),(1,'rec2'),(1,'rec3'),(1,'rec4')
INSERT INTO @t2 (tID,SomeField,AnotherField) VALUES (1,'s106','here'),(1,'s12','just'),(1,'s13','sample')
INSERT INTO @t3 (field1,field2) VALUES ('field1 Value','field2 Value')
通緝的結果(最終):
<ThirdTable ID="1" field1="field1 Value" field2="field2 Value">
<FirstTable ID="1" tID="1" SomeField="rec1" />
<FirstTable ID="2" tID="1" SomeField="rec2" />
<FirstTable ID="3" tID="1" SomeField="rec3" />
<FirstTable ID="4" tID="1" SomeField="rec4" />
<AnotherTable ID="1" tID="1" SomeField="s106" AnotherField="here" />
<AnotherTable ID="2" tID="1" SomeField="s12" AnotherField="just" />
<AnotherTable ID="3" tID="1" SomeField="s13" AnotherField="sample" />
</ThirdTable>
哇,這太神奇了!再次感謝! –
@ArkadiyV。再次,快樂幫助...有趣的結構。我想我可能會使用這樣的東西 –
是的,我發現結構是最優化的,然後讓每個表分開或DataSet。但是,如果表't1'沒有記錄,我發現有趣的事情,表't2'也不會添加... –