问题
I have a stored procedure generating XML with FOR XML
functionality. When I run the stored procedure, I get beautifully formatted XML as a result.
When I try to export this result into a file with bcp
declare @sql varchar(8000)
select @sql = 'bcp "exec sp_ExportXml" queryout C:\Filename.xml -S (local) -T -w'
exec master..xp_cmdshell @sql
I get a badly formatted with line breaks inside the xml tags e.g.
<Division>3</Divi
sion>
I am completely clueless, I tried several different parameters for bcp queryout
but always getting the same result.
Any ideas are highly appreciated! Thanks
回答1:
Is the simple solution here just to use the -r switch?
I faced the same issue and was thinking there must be a simple answer, after some searching around I gave it a go and it worked for me.
select @sql = 'bcp "exec sp_ExportXml" queryout C:\Filename.xml -S (local) -T -w -r'
Apologies if you have already tried this but to my knowledge, far from an expert on BCP, the above example will override the Row Terminator will be nothing, hence no dodgy line break in the middle of element tags.
回答2:
I have faced a similar issue, this happens because of he size of the column_width
size of the results being returned, I think he default width is 2034, you can use the SQLCMD command and set -w property to overcome this.
This link might be helpful, http://connect.microsoft.com/SQLServer/feedback/details/786004/sqlcmd-with-xml-on-break-lines-on-large-output
回答3:
I could solve this by not using bcp but instead run ExecuteXmlReader on the SqlCommand as suggested here: http://support.microsoft.com/kb/310378
回答4:
Here is powershell script that is able to output xml into a file without inserting line breaks after the 2034 character:
# Retrieving XML Data Through an XML Reader
# Create SqlConnection object and define connection string
$con = New-Object System.Data.SqlClient.SqlConnection
$con.ConnectionString = "Server=your.servername.local\yourInstanceName;Database=yourDBname;Integrated Security=True"
$con.open()
# Create SqlCommand object, define command text, and set the connection
$cmd = New-Object System.Data.SqlClient.SqlCommand
$cmd.CommandText = "EXEC your query"
$cmd.Connection = $con
# Create XmlReader
$xr = $cmd.ExecuteXmlReader()
# Create XmlDataDocument object for dataset
$xd = New-Object System.Xml.XmlDataDocument
# Load the XML data document
$xd.Load($xr)
# Close the DataReader and the connection
$xr.Close()
$con.Close()
$xd.InnerXml > .\yourFileName.xml
回答5:
Actually, SQL Server doesn't insert any line breaks in the resulting XML, to the best of my knowledge. The fact that it looks nicely formatted in SSMS is because SSMS formats it nicely. IOW, the presentation depends on the editor used.
If you've really encountered a case that SQL Server inserts line breaks, this would be a bug, and a very serious one.
来源:https://stackoverflow.com/questions/23321341/sql-server-bcp-export-xml-format