如何使用FOR XML AUTO子句将特定列作为元素返回

时间:2018-03-03 14:35:41

标签: sql-server xml for-xml

我需要返回一个特定的列作为在sql server中使用FOR XML AUTO子句返回的xml中的元素。自动返回将所有字段转换为相应元素的属性。好的,但是我需要一个领域作为一个元素。

我有两张桌子:

data

我之间有以下关系:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Table1](
    [Id] [int] NULL,
    [Nome] [varchar](50) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Table2]    Script Date: 02/03/2018 16:24:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Table2](
    [Id] [int] NULL,
    [DataVencimento] [date] NULL,
    [Table1_Id] [int] NULL
) ON [PRIMARY]
GO
INSERT [dbo].[Table1] ([Id], [Nome]) VALUES (1, N'AAA')
GO
INSERT [dbo].[Table1] ([Id], [Nome]) VALUES (2, N'BBB')
GO
INSERT [dbo].[Table1] ([Id], [Nome]) VALUES (3, N'CCC')
GO
INSERT [dbo].[Table2] ([Id], [DataVencimento], [Table1_Id]) VALUES (1, CAST(N'2018-01-01' AS Date), 1)
GO
INSERT [dbo].[Table2] ([Id], [DataVencimento], [Table1_Id]) VALUES (2, CAST(N'2018-01-02' AS Date), 2)
GO
INSERT [dbo].[Table2] ([Id], [DataVencimento], [Table1_Id]) VALUES (3, CAST(N'2018-01-03' AS Date), 2)
GO

返回:

select 
    Table1.Id,
    Table1.Nome,
    Table2.Id,
    Table2.DataVencimento
from Table1 
    inner join Table2 on Table2.Table1_Id = Table1.Id
    order by Table1.Id, Table2.Id
for xml auto, root('ArrayOfTable1')

但我需要DataVencimento作为一个元素,如下所示:

<ArrayOfTable1>
  <Table1 Id="1" Nome="AAA">
    <Table2 Id="1" DataVencimento="2018-01-01" />
  </Table1>
  <Table1 Id="2" Nome="BBB">
    <Table2 Id="2" DataVencimento="2018-01-02" />
    <Table2 Id="3" DataVencimento="2018-01-03" />
  </Table1>
</ArrayOfTable1>

怎么做?

3 个答案:

答案 0 :(得分:1)

如果有更清洁的解决方案,我现在不会这样做但是这样的事情应该有效:

Note that the spreadsheet is NOT physically opened on the client side.
 // It is opened on the server only (for modification by the script).

答案 1 :(得分:1)

select 
    Table1.ID,
    Table1.Nome,
    Table2.Id,
    (select table2.DataVencimento for xml path(''), elements, type)
from Table1 
    inner join Table2 on Table2.Table1_Id = Table1.Id
order by Table1.Id, Table2.Id
for xml auto, root('ArrayOfTable1')

输出:

<ArrayOfTable1>
  <Table1 ID="1" Nome="AAA">
    <Table2 Id="1">
      <DataVencimento>2018-01-01</DataVencimento>
    </Table2>
  </Table1>
<Table1 ID="2" Nome="BBB">
  <Table2 Id="2">
    <DataVencimento>2018-01-02</DataVencimento>
  </Table2>
  <Table2 Id="3">
    <DataVencimento>2018-01-03</DataVencimento>
  </Table2>
</Table1>
</ArrayOfTable1>

http://sqlfiddle.com/#!18/71fe9/29

答案 2 :(得分:0)

在大多数情况下,FOR XML PATH()是首选方法。使用PATH,您可以完全控制输出。没有什么是自动 ...

尝试一下:

SELECT t1.Id AS [@id]
      ,t1.Nome AS [@Nome]
      ,(
        SELECT t2.Id AS [@Id]
              ,t2.DataVencimento
        FROM dbo.Table2 AS t2
        WHERE t1.Id=t2.Table1_Id
        ORDER BY t2.Id
        FOR XML PATH('Table2'),TYPE
       )
FROM dbo.Table1 AS t1
WHERE EXISTS(SELECT 1 FROM dbo.Table2 WHERE Table2.Table1_Id=t1.Id)
ORDER BY t1.Id
FOR XML PATH('Table1'), ROOT('ArrayOfTable1');