How to execute a stored procedure within C# program

前端 未结 13 1653
别跟我提以往
别跟我提以往 2020-11-22 00:10

I want to execute this stored procedure from a C# program.

I have written the following stored procedure in a SqlServer query window and saved it as stored1:

<
13条回答
  •  -上瘾入骨i
    2020-11-22 00:35

    SqlConnection conn = null;
    SqlDataReader rdr  = null;
    conn = new SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI");
    conn.Open();
    
    // 1.  create a command object identifying
    //     the stored procedure
    SqlCommand cmd  = new SqlCommand("CustOrderHist", conn);
    
    // 2. set the command object so it knows
    //    to execute a stored procedure
    cmd.CommandType = CommandType.StoredProcedure;
    
    // 3. add parameter to command, which
    //    will be passed to the stored procedure
    cmd.Parameters.Add(new SqlParameter("@CustomerID", custId));
    
    // execute the command
    rdr = cmd.ExecuteReader();
    
    // iterate through results, printing each to console
    while (rdr.Read())
    {
        Console.WriteLine("Product: {0,-35} Total: {1,2}", rdr["ProductName"], rdr["Total"]);
    }
    

提交回复
热议问题