Sna*_*yes 4 .net c# t-sql sql-server asp.net-mvc-3
我有一个示例代码
aCommand.CommandType = CommandType.StoredProcedure;
aCommand.Parameters.AddWithValue("@book_id", bookID);
aCommand.Parameters.AddWithValue("@user_id", userID);
之后我想用以下方法执行一个简单的查询CommandText:
aCommand.CommandText = "SELECT * FROM aTABLE";
aCommand.ExecuteNonQuery();
但是错误发生了:
例外:找不到存储过程'SELECT*FROM aTABLE'
在这种情况下,我必须创建一个新的SqlCommand对象实例?
这是一种使用同一个SqlCommand对象来避免创建一个的方法吗?
Joh*_*Woo 10
它应该是
aCommand.CommandType = CommandType.Text
实际上,默认值CommandType是CommandType.Text
问题是,你有重用的SqlCommand那CommandType是StoredProcedure,但要执行与普通的SQL查询CommandType.Text.
"在这种情况下,我必须创建一个新的SqlCommand对象实例?"
我建议这样做以避免这种混淆.创建一个SqlCommand不是那么昂贵,你需要重用它.实际上构造函数只不过是设置属性.
来自ILSpy:
// System.Data.SqlClient.SqlCommand
// this() does only call _SuppressFinalize
public SqlCommand(string cmdText, SqlConnection connection) : this()
{
    this.CommandText = cmdText;
    this.Connection = connection;
}
aCommand.CommandType = CommandType.StoredProcedure;
aCommand.Parameters.AddWithValue("@book_id", bookID);
aCommand.Parameters.AddWithValue("@user_id", userID);
指定您调用的存储过程名称
aCommand.CommandText=yourstoredprocedurename;
aCommand.ExecuteNonQuery();
然后调用你的select和sqlreader来获得结果
bCommand.CommandType = CommandType.Text
bCommand.CommandText = "SELECT * FROM aTABLE";
SqlDataReader rdr = bCommand.ExecuteReader();