我之前带着这个任务来到了 StackOverflow: MS SQL2005 Query/Stored Proc Results To Text using SqlCommand or any other method
有人告诉我自己构建字符串,以便获得与 SQL Managment Studio 的 Results To Text (Cntrl + T) 相同的结果
我现在遇到了一个问题,如何动态确定列的宽度?还有那些是 VARCHAR(MAX) 的列呢?我完全不知道事先会进入 SqlDataReader 的内容。
这是我到目前为止的代码,我基本上需要消除 PADDING_LENGTH 并动态替换它的值。
我从网上某处获取了基本代码。(谁先写的,谢谢你)
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();
}
干杯,凯。