Hello,
I've come to StackOverflow before with this quest: http://stackoverflow.com/questions/547040/ms-sql2005-query-stored-proc-results-to-text-using-sqlcommand-or-such
I was told to build the string myself so that I get the same results as from SQL Managment Studio's Results To Text (Cntrl + T)
I have now run into a problem, how do I determine the width of the column dynamically? Also what about columns that are VARCHAR(MAX)? I have absolutely no idea what will come into the SqlDataReader before hand.
Here's the code I have so far, I essentially need to eliminated PADDING_LENGTH and replace its value dynamically.
I took the basic code from the net somewhere. (Whoever wrote it first, my thanks to you)
StringBuilder sb = new StringBuilder();
private void GenerateResultsText(SqlDataReader reader)
{
const int PADDING_LENGTH = 40;
do
{
// Create new data table
DataTable schemaTable = reader.GetSchemaTable();
if (schemaTable != null)
{
// A query returning records was executed
for (int i = 0; i < schemaTable.Rows.Count; i++)
{
DataRow dataRow = schemaTable.Rows[i];
// Create a column name that is unique in the data table
string columnName = (string)dataRow["ColumnName"];
//Add to Results String.
sb.Append(String.Format("{0, " + -1 * PADDING_LENGTH + "}", columnName));
}
sb.Append(Environment.NewLine);
//Add markers to seperate Row entries from Column names.
const string columnRowSeperator = "-----"; //Keep it to a multiple of 5.
for (int i = 0; i < schemaTable.Rows.Count; i++)
{
for (int j = 0; j < PADDING_LENGTH / columnRowSeperator.Length; j++)
sb.Append(columnRowSeperator);
}
sb.Append(Environment.NewLine);
// Fill the data table we just created
while (reader.Read())
{
Object temp;
for (int i = 0; i < reader.FieldCount; i++)
{
temp = reader.GetValue(i);
sb.Append(String.Format("{0, " + -1 * PADDING_LENGTH + "}", temp.ToString()));
}
sb.Append(Environment.NewLine);
}
//Add newlines to seperate tables.
sb.Append(Environment.NewLine + Environment.NewLine);
}
}
while (reader.NextResult());
reader.Close();
reader.Dispose();
}
Cheers, Kai.