永远的SKYFEI
喜欢在阳光下,光着脊梁,挥汗如雨地工作,每次回头擦汗,看到的都是成就!
reference: http://aspnetresources.com/blog/executescalar_truncates_xml.aspx

 

Microsoft’s KB article Q310378: XML Data Is Truncated When You Use SqlDataReader, and all of a sudden it became clear:

When you read Extensible Markup Language (XML) data from Microsoft SQL Server by using the SqlDataReader object, the XML in the first column of the first row is truncated at 2,033 characters. You expect all of the contents of the XML data to be contained in a single row and column.

This behavior occurs because, for XML results greater than 2,033 characters in length, SQL Server returns the XML in multiple rows of 2,033 characters each.

The keyword here is multiple. If you call ExecuteScalar you have no way of getting anything but the very first column of the very first row, so this method is a dead end.

Another KB article, Q316701: Use the ExecuteXmlReader Method of the SqlCommand Class in Visual C# .NET shows how to bypass this problem by reading in a loop until all rows are read. I ended up with this:

connection.Open ();
rdr = command.ExecuteXmlReader ();
rdr.Read ();

while (rdr.ReadState != ReadState.EndOfFile) 
{
 result += rdr.ReadOuterXml ();
}

rdr.Close ();

For greater efficiency I’d use a StringBuilder here to concatenate chunks of text.

posted on 2008-01-17 18:39  skyfei  阅读(351)  评论(0编辑  收藏  举报