使用FOR XML子句时如何保存XML输出?

时间:2017-06-30 20:53:54

标签: sql xml tsql

所以,我试图将我的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

结果是这样,没有保存文件...... enter image description here

1 个答案:

答案 0 :(得分:1)

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

enter image description here

enter image description here

就传递表格而言,只需在' FOR XML PATH(' SyncProductionPerformance')之前添加from子句'