【问题标题】:How to save XML output when using FOR XML clause?使用 FOR XML 子句时如何保存 XML 输出?
【发布时间】:2017-06-30 20:53:53
【问题描述】:

所以,我正在尝试将我的 SQL 查询结果保存为 XML 文件。我已经让我的查询结果输出了我想要的 XML,但我最终会将其用作存储过程,因此我需要能够将结果输出为 XML 文件。

我尝试过使用xp_cmdshell 方法...

declare @cmd nvarchar(255);

select @cmd = ' bcp " Select
    (
    Select GetDate() AS [ApplicationArea/CreationDateTime], BODID.BODID AS [ApplicationArea/BODID]
    From BODID
    Where BODID = "ME-COIL-MESSAGE"
    For XML Path(''), Type
    ),
    (
    Select 
        (
        Select pp.EquipmentID AS [Location/EquipmentID], pp.EquipmentElementLevel AS [Location/EquipmentElementLevel] , GetDate() AS [PublishedDate]
        From ProductionPerformance AS pp
        For XML Path(''), Root("ProductionPerformance"), Type
        ),
        (
        Select ProductionResponse.ID,
            (
            Select Sample.MaterialLotID AS [ID],
                (
                Select MaterialLotID, ID AS [MaterialActualProperty/ID], ValueString AS [MaterialActualProperty/Value/ValueString] 
                From Sample
                For XML Path(''), Root("MaterialActual") , Type
                )
            From Sample
            Where MaterialLotID is not null 
            For XML Path(''), Root("SegmentResponse"), Type
            )
        From ProductionResponse
        For XML Path(''), Root("ProductionResponse"), Type
        )
    For XML Path(''), Root("DataArea"), Type
    )
For XML Path(''), Root("SyncProductionPerformance"), Type" ' + 'queryout "C:\Users\spakuresa\Documents\Out\sample.xml" -S YOUR_INSTANCE_NAME -T -w -r -t -x';

exec xp_cmdshell @cmd
go

结果是这样,没有文件被保存...

【问题讨论】:

  • 只需在 FOR XML 之前添加 FROM [table_name]。我还建议为你的家庭作业做一些你自己的“谷歌搜索”。像这样的谷歌查询应该会给你足够的答案:google.com.au/…

标签: sql xml tsql


【解决方案1】:

要将数据保存到 xml 文件,请打开 SQLCMD 模式,然后将 ':out' 参数添加到脚本顶部。

至于“传递表格”,只需在“FOR XML PATH('SyncProductionPerformance')”之前添加 from 子句

【讨论】:

  • 它并没有按照我希望的方式进行格式化,但确实有效!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-06
  • 1970-01-01
  • 2023-03-07
  • 2017-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多