2015-02-24 124 views
1

我有一个运行名为sp_GetEmployeeByID以下存储过程一个MVC应用程序:如何通过C#中的存储过程传递参数

@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并为sprocs @ID参数传递一个参数。

回答

4

添加Parameter的命令:

SqlCommand sprocCmd = new SqlCommand("sp_GetEmployeeByID");      
sprocCmd.CommandType = System.Data.CommandType.StoredProcedure; 
sprocCmd.Parameters.AddWithValue("@ID", ID) 
+0

谢谢你,那正是我一直在寻找。 – 2015-02-24 22:26:03

相关问题