将声明附加到XML文件

时间:2009-04-28 05:40:25

标签: sql xml tsql

通过使用bcp作为

调用proc,从数据库中创建XML
SET @SQL= 'bcp "exec dbo.proc" queryout '+ @FileName +' -w -r -t  -Sdd\SQL2005 -T '

(proc下面制作) 一切都很好=&gt;根据需要创建XML。 现在的任务是将声明添加到此XML(<?xml version="1.0" ?>

如何在下面的proc中实现,或者用其他文件(包含声明)来结束XML

SELECT  ( SELECT TOP 1
                    ShiftDate AS "ShiftDate",
                    Shift AS "Shift"
          FROM      [TableName]
        FOR
          XML PATH(''),
              TYPE
        ),
        ( SELECT    EquipmentId AS "WasheryProductionDetails/EquipmentCode",
                    'n/a' AS "WasheryProductionDetails/ActivityCode",
                    'n/a' AS "WasheryProductionDetails/ReasonCode",
                    Parentmaterial AS "WasheryProductionDetails/WasheryFeed/MaterialCode",
                    ParentStockpile AS "WasheryProductionDetails/WasheryFeed/ROMStockpileCode",
                    CAST(ParentTonnes AS DECIMAL(18, 4)) AS "WasheryProductionDetails/WasheryFeed/FeedTonnes",
                    ChildMaterial AS "WasheryProductionDetails/WasheryOutput/MaterialCode",
                    ChildStockpile AS "WasheryProductionDetails/WasheryOutput/ProductStockpileCode",
                    CAST(ChildTonnes AS DECIMAL(18, 4)) AS "WasheryProductionDetails/WasheryOutput/ProductTonnes"
          FROM      [TableName]
        FOR
          XML PATH(''),
              TYPE
        )
FOR     XML PATH(''),
            ROOT('WasheryProduction')

由于

2 个答案:

答案 0 :(得分:2)

This page建议您需要对声明进行硬编码:

SELECT

'<?xml version="1.0" ?>'

+
SELECT  ( SELECT TOP 1
... rest of your code goes here...

编辑:将“UNION ALL”(这显然是错误的)更改为“+”(均来自链接页面。)

答案 1 :(得分:2)

Declare @SQL varchar(8000)
Declare @xml xml
Declare @strXML as varchar(max)

set @xml = (select * from <tableName> for xml path(''))
set @strXML='< ? xml version = "1.0" ? >' + convert(varchar(max), @xml)

select @strXML

set @SQL ='bcp "select '''+@strXML+'''"  QueryOut "C:\xmlFile.xml" -r -w -t -T -S '

Exec master..xp_cmdshell @SQL