我有一个 SQL SELECT 语句,直到运行时才知道,它可能包含 JOIN 和内部选择。我需要从 C# 中确定语句返回结果的每一列的名称和数据类型。我倾向于做类似的事情:
string orginalSelectStatement = "SELECT * FROM MyTable";
string selectStatement = string.Format("SELECT TOP 0 * FROM ({0}) s", orginalSelectStatement);
SqlConnection connection = new SqlConnection(@"MyConnectionString");
SqlDataAdapter adapter = new SqlDataAdapter(selectStatement, connection);
DataTable table = new DataTable();
adapter.Fill(table);
foreach (DataColumn column in table.Columns)
{
Console.WriteLine("Name: {0}; Type: {1}", column.ColumnName, column.DataType);
}
有没有更好的方法来做我想做的事情?“更好”是指完成相同任务的资源较少的方式或完成相同任务的更确定的方式(即,据我所知,我刚刚给出的代码片段在某些情况下会失败)。
解决方案:首先,我的TOP 0
技巧很糟糕,即对于这样的事情:
SELECT TOP 0 * FROM (SELECT 0 AS A, 1 AS A) S
换句话说,在子选择中,如果两个事物被别名为相同的名称,则会引发错误。所以它不在图片中。但是,为了完整起见,我继续测试了它,以及两个建议的解决方案: SET FMTONLY ON
和GetSchemaTable
.
以下是结果(每 1,000 个查询以毫秒为单位):
模式时间:3130
TOP 0 时间:2808
FMTONLY 上线时间:2937
我的建议是GetSchemaTable
,因为它更有可能通过删除SET FMTONLY ON
as valid SQL 来适应未来,并且它解决了别名问题,即使它稍微慢一些。 但是,如果您“知道”重复的列名永远不会成为问题,那么TOP 0
它GetSchemaTable
比SET FMTONLY ON
.
这是我的实验代码:
int schemaTime = 0;
int topTime = 0;
int fmtOnTime = 0;
SqlConnection connection = new SqlConnection(@"MyConnectionString");
connection.Open();
SqlCommand schemaCommand = new SqlCommand("SELECT * FROM MyTable", connection);
SqlCommand topCommand = new SqlCommand("SELECT TOP 0 * FROM (SELECT * FROM MyTable) S", connection);
SqlCommand fmtOnCommand = new SqlCommand("SET FMTONLY ON; SELECT * FROM MyTable", connection);
for (int i = 0; i < 1000; i++)
{
{
DateTime start = DateTime.Now;
using (SqlDataReader reader = schemaCommand.ExecuteReader(CommandBehavior.SchemaOnly))
{
DataTable table = reader.GetSchemaTable();
}
DateTime stop = DateTime.Now;
TimeSpan span = stop - start;
schemaTime += span.Milliseconds;
}
{
DateTime start = DateTime.Now;
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(topCommand);
adapter.Fill(table);
DateTime stop = DateTime.Now;
TimeSpan span = stop - start;
topTime += span.Milliseconds;
}
{
DateTime start = DateTime.Now;
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(fmtOnCommand);
adapter.Fill(table);
DateTime stop = DateTime.Now;
TimeSpan span = stop - start;
fmtOnTime += span.Milliseconds;
}
}
Console.WriteLine("Schema Time: " + schemaTime);
Console.WriteLine("TOP 0 Time: " + topTime);
Console.WriteLine("FMTONLY ON Time: " + fmtOnTime);
connection.Close();