sql - 从不同的表中获取 XML

标签 sql sql-server xml tsql

祝你有个美好的一天!

我有一个问题。无法了解如何在 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 here

新评论(已编辑)

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>

最佳答案

Select [root] = cast((Select * From @t1 for xml raw('FirstTable'))
                    +(Select * From @t2 for xml raw('AnotherTable'))
                as xml)
For XML Path(''),Type

返回

<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>

关于sql - 从不同的表中获取 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44337813/

相关文章:

sql - Snowflake中的语句绑定(bind)/执行顺序

SQL - 如果数组包含特定项目则过滤行

MySQL 如何从 varchar 列中获取精确的整数值

sql-server - 可以为链接服务器调用的每个查询设置 SQL Server 远程查询超时吗?

sql - "clustered"中的 "clustered index"是什么意思?

css - 动画 svg+xml base 64 css 背景在 IE 中不起作用

java - 使用Java的PostgreSQL上的Money数据

sql-server - TSQL - 独特的问题

xml - 需要属性但也允许 nil 的 XSD

java - GPS map 不要撒播它