将 Command.Prepare 与 SELECT 一起使用时,是否需要将 SELECT 列指定为输出参数?
我尝试将 Command.Prepare 与具有单个输入参数的 CommandType.Text 查询结合使用。 SELECT 有几列,我用 DataReader 提取这些列。在调用 Command.Prepare() 之前,是否需要将每个选择列指定为输出参数?即使我不需要指定它们,如果我指定它们,性能会提高吗?
示例代码:
using(var connection = new SqlConnection("connection string")
{
connection.Open();
using(var cmd = new SqlCommand(null, Connection))
{
cmd.CommandText = "SELECT COLUMN1, COLUMN2, COLUMN3 " +
"FROM TABLE1 WHERE COLUMN4 = @thing";
cmd.Parameters.Add(new SqlParameter
{
ParameterName = "@thing",
DbType = SqlDbType.Int,
Value = 1
});
//should I add output parms for COLUMN1, COLUMN2, COLUMN3?
cmd.Prepare();
using(var reader = cmd.ExecuteReader())
{
//get stuff out of reader
}
}
}
I'm trying to use Command.Prepare
with a CommandType.Text
query that has a single input parameter. The SELECT has several columns that I am extracting with a DataReader. Do I need to specify each of the select columns as output parameters before calling Command.Prepare()
? Even if I don't need to specify them, will performance improve if I do?
Example code:
using(var connection = new SqlConnection("connection string")
{
connection.Open();
using(var cmd = new SqlCommand(null, Connection))
{
cmd.CommandText = "SELECT COLUMN1, COLUMN2, COLUMN3 " +
"FROM TABLE1 WHERE COLUMN4 = @thing";
cmd.Parameters.Add(new SqlParameter
{
ParameterName = "@thing",
DbType = SqlDbType.Int,
Value = 1
});
//should I add output parms for COLUMN1, COLUMN2, COLUMN3?
cmd.Prepare();
using(var reader = cmd.ExecuteReader())
{
//get stuff out of reader
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,您不需要输出参数。您只需以正常方式从阅读器中获取结果即可。
事实上,将列作为输出参数是没有意义的,因为每行每列都有一个值,而不是整个调用只有一个值。
No, you don't need output parameters. You just get the results out of the reader in the normal way.
In fact, having the columns as output parameters wouldn't make sense, as you'll have a value per column per row rather than just one value for the whole call.
Linq 的
DataContext
提供了比SqlCommand
更简单的方法来使用参数:虽然语法看起来像
string.Format
,但{0}传递给 ExecuteQuery 的
最终成为一个真正的 SQL 参数。Linq's
DataContext
provides a much easier way to use parameters thanSqlCommand
:Although the syntax looks like
string.Format
, the{0}
passed toExecuteQuery
ends up being a real SQL parameter.