我有一个运行以下名为sp_GetEmployeeByID的sproc的MVC应用程序:
@ID int = 0
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT @ID, *
from tblEmployee
where ID = @ID
并且调用它的方法需要传递int参数但是我似乎无法弄明白,这是我到目前为止所拥有的:
public Employee GetSingleEmployee(int ID)
{
string connectionString = ConfigurationManager.ConnectionStrings["KVKDb"].ConnectionString;
Employee emp = new Employee();
using (SqlConnection connect = new SqlConnection(connectionString))
{
SqlCommand sprocCmd = new SqlCommand("sp_GetEmployeeByID " + ID, connect); sprocCmd.CommandType = System.Data.CommandType.StoredProcedure;
connect.Open();
SqlDataReader rdr = sprocCmd.ExecuteReader();
while (rdr.Read() == true)
{
Employee employee = new Employee();
employee.ID = Convert.ToInt32(rdr["ID"]);
employee.City = rdr["City"].ToString();
employee.DateOfBirth = Convert.ToDateTime(rdr["DateOfBirth"]);
employee.Gender = rdr["Gender"].ToString();
employee.Name = rdr["Name"].ToString();
emp = employee;
}
}
return emp;
}
显而易见的问题是没有名为sp_GetEmployeeByID int ID的sproc。我想知道如何调用该sproc并传递sprocs @ID参数的参数。
答案 0 :(得分:3)
在命令中添加Parameter
:
SqlCommand sprocCmd = new SqlCommand("sp_GetEmployeeByID");
sprocCmd.CommandType = System.Data.CommandType.StoredProcedure;
sprocCmd.Parameters.AddWithValue("@ID", ID)