如何通过 C# 为 sproc 传递参数

How to pass parameter for sproc via C#

我有一个运行以下存储过程的 MVC 应用程序,名为 sp_GetEmployeeByID:

    @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 参数传递参数。

在命令中添加一个Parameter

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