Note that there are some explanatory texts on larger screens.

plurals
  1. POGetting Column Width from SqlDataReader
    primarykey
    data
    text
    <p>I've come to StackOverflow before with this quest: <a href="https://stackoverflow.com/questions/547040/ms-sql2005-query-stored-proc-results-to-text-using-sqlcommand-or-such">MS SQL2005 Query/Stored Proc Results To Text using SqlCommand or any other method</a></p> <p>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) </p> <p>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. </p> <p>Here's the code I have so far, I essentially need to eliminated PADDING_LENGTH and replace its value dynamically. </p> <p>I took the basic code from the net somewhere. (Whoever wrote it first, my thanks to you)</p> <pre><code>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 &lt; 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 &lt; schemaTable.Rows.Count; i++) { for (int j = 0; j &lt; 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 &lt; 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(); } </code></pre> <p>Cheers, Kai. </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload