使用参数运行存储过程
本文关键字:存储过程 运行 参数 | 更新日期: 2023-09-27 18:36:19
我有一个方法可以获取sql连接并连接。创建一个新命令,添加一些参数,然后运行适配器来填充数据表。但是我收到错误说我没有提供参数 - 即使我清除了。
你认为这里出了什么问题?
public static DataTable getStatsPaged(int currentPage, int pageSize, int year, int month, int day, int logType, int itemid, string stat)
{
using (SqlConnection connection = sqldb.getSqlConnection("db2"))
{
connection.Open();
using (SqlCommand command = new SqlCommand("stp_FidusTrak_"+stat+"_paged", connection))
{
command.Parameters.Add(new SqlParameter("@RETURN_VALUE", SqlDbType.Int, 4, ParameterDirection.ReturnValue, false, ((System.Byte)(0)), ((System.Byte)(0)), "", DataRowVersion.Current, null));
command.Parameters.Add(new SqlParameter("@CurrentPage", currentPage));
command.Parameters.Add(new SqlParameter("@PageSize", pageSize));
command.Parameters.Add(new SqlParameter("@Year", year));
command.Parameters.Add(new SqlParameter("@Month", month));
command.Parameters.Add(new SqlParameter("@Day", day));
//error is this logType
//Procedure or function 'stp_FidusTrak_SearchParameterSelect_paged' expects parameter '@LogType', which was not supplied.
command.Parameters.Add(new SqlParameter("@LogType", -10));
command.Parameters.Add(new SqlParameter("@itemId", itemid));
command.Parameters.Add(new SqlParameter("@TotalRecords", SqlDbType.Int, 4, ParameterDirection.Output, false, ((System.Byte)(0)), ((System.Byte)(0)), "", DataRowVersion.Current, null));
command.Parameters.Add(new SqlParameter("@FirstDate", SqlDbType.SmallDateTime, 4, ParameterDirection.Output, false, ((System.Byte)(0)), ((System.Byte)(0)), "", DataRowVersion.Current, null));
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
adapter.SelectCommand = command;
DataTable table = new DataTable();
adapter.Fill(table);
return table;
}
}
}
}
它通常会作为变量传入,但即使我只是将其写为 -10,它仍然说不提供。
有人有想法吗?也许我的使用错误?
谢谢。
您应该指定命令类型,该类型必须StoredProcedure
。请参阅此处的文档:http://msdn.microsoft.com/en-us/library/system.data.common.dbcommand.commandtype.aspx
您尚未告诉 ADO.NET 这是您正在调用的存储过程。
添加此行:
using (SqlCommand command = new SqlCommand("stp_FidusTrak_"+stat+"_paged", connection))
{
// tell it that it's a stored procedure
command.CommandType = CommandType.StoredProcedure;
在代码中使用 SP 时必须插入此行。
command.CommandType = CommandType.StoredProcedure;
检查您在存储过程中传递LogType
参数类型,并提到StoredProcedure
命令对象的类型,因为它采用默认Text
类型
试试下面的行:-
command.Parameters.Add(new SqlParameter("@LogType", "-10"));