输出XML时出现T-SQL bcp语法问题

时间:2016-05-22 21:03:53

标签: sql-server xml tsql

我在存储过程中有以下bcp命令。存储过程构造如下:

SET @sqlCmd = 'bcp "' + @sqlStr + '" queryout "' + @offersFilename + '" -w -T';

EXEC xp_cmdshell @sqlCmd;

当我尝试运行它时,我得到了bcp使用响应,这意味着我的@sqlCmd中存在一些语法错误。

使用PRINT @sqlCMD,我得到以下打印输出。有人可以告诉我哪里弄错了。感谢。

bcp "select custID as ""@id"", 
        (
          SELECT familyDesc as ""familyDesc"",
               upc as ""upc"",
               itemDesc as ""itemDescription"",
               offerCode as ""offerCode"",
               offerDesc as ""offerDesc"",
               validFrom as ""validFrom"",
               validTo as ""validTo"",
               cast(round(price,2) as decimal(19,2)) as ""price"",
               imageURL as ""imageURL""
           FROM tblCustomerOffers t2 where t1.custID=t2.custID
           for XML PATH('Offer'), TYPE
        )
        from tblCustomerOffers t1
        group by custID
        FOR XML PATH('Customer'), ROOT ('Offers'), ELEMENTS"
queryout "D:\offers\customerOffers.xml" -w -T

1 个答案:

答案 0 :(得分:2)

我在工作中遇到过类似的问题。

使调试变得更容易的一种方法是,不是使用bcp的 queryout 命令,而是创建全局临时表来存储查询结果。然后使用bcp的 out 命令导出该单个记录。

例如,

CREATE TABLE ##FooResults (result XML)
INSERT INTO ##FooResults
SELECT (
    SELECT Bar AS [Bar]
    FROM Foo
    FOR XML PATH('Foo')
)

DECLARE @ExportXmlCommand VARCHAR(4000) = 'bcp ##FooResults out "C:\foo.xml" -w -T'
EXEC xp_cmdshell @ExportXmlCommand

DROP TABLE ##FooResults

这样做的好处是,它允许您利用SSMS的语法突出显示,并在出现错误时提供更详细的结果。

缺点是所有XML都被压缩成单行。

为了解决这个问题,我设计了一个解决方法,运行一个Powershell脚本,该脚本将重新格式化XML,使其可读。

Param(
    [string]$infile,
    [string]$outfile,
    [int]$indent = 4
)

function Format-XML {
    Param(
        [xml]$xml,
        [int]$indent = 4
    )
    $StringWriter = New-Object System.IO.StringWriter 
    $XmlWriter = New-Object System.XMl.XmlTextWriter $StringWriter 
    $xmlWriter.Formatting = "indented"
    $xmlWriter.Indentation = $indent
    $xml.WriteContentTo($XmlWriter) 
    $XmlWriter.Flush() 
    $StringWriter.Flush() 
    Write-Output $StringWriter.ToString() 
}

$result = Format-XML ([System.Xml.XmlDocument](cat (Resolve-Path $infile))) $indent
$result | Set-Content "$outfile"

(改编自https://blogs.msdn.microsoft.com/powershell/2008/01/18/format-xml/

所以把它们放在一起,最后几行最终看起来像这样:

DECLARE @ExportXmlCommand VARCHAR(4000) = 'bcp ##FooResults out "C:\foo.temp.xml" -w -T'
DECLARE @FormatXmlCommand VARCHAR(4000) = 'PowerShell.exe -ExecutionPolicy Bypass -File "C:\Format-Xml.ps1" "C:\foo.temp.xml" "C:\foo.xml"'
DECLARE @DeleteTempXmlCommand VARCHAR(4000) = 'del "C:\foo.temp.xml"'

EXEC xp_cmdshell @ExportXmlCommand
EXEC xp_cmdshell @FormatXmlCommand
EXEC xp_cmdshell @DeleteTempXmlCommand

我希望这可以帮助您找到错误的原因!

埃里克