C Calling Stored Procedure Detailed Explanation of With Return Value Parameter Input and Output etc

  • 2021-10-13 08:22:57
  • OfStack

This article illustrates how C # calls stored procedures. Share it for your reference, as follows:


CREATE PROCEDURE [dbo].[GetNameById]
 @studentid varchar(8),
 @studentname nvarchar(50) OUTPUT
AS
BEGIN
 SELECT @studentname=studentname FROM student
  WHERE studentid=@studentid
 if @@Error<>0
 RETURN -1
 else
 RETURN 0
END


using (SqlConnection conn = new SqlConnection(connStr))
{
  try
  {
    SqlCommand cmd = new SqlCommand("GetNameById", conn);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@studentid", "09888888");    // Assign values to input parameters 
    SqlParameter parOutput =cmd.Parameters.Add("@studentname", SqlDbType.NVarChar, 50);    // Define output parameters 
    parOutput.Direction = ParameterDirection.Output;    // Parameter type is Output
    SqlParameter parReturn = new SqlParameter("@return", SqlDbType.Int);
    parReturn.Direction = ParameterDirection.ReturnValue;     // Parameter type is ReturnValue
    cmd.Parameters.Add(parReturn);
    conn.Open();
    cmd.ExecuteNonQuery();
    MessageBox.Show(parOutput.Value.ToString());  // Displays the value of the output parameter 
    MessageBox.Show(parReturn.Value.ToString());    // Display return value 
  }
  catch (System.Exception ex)
  {
    MessageBox.Show(ex.Message);
  }
}


Create PROCEDURE AddOrderTran
  @country nvarchar(100),
  @adds nvarchar(100),
  @ynames nvarchar(100),
  @pids nvarchar(100),
  @cellp nvarchar(100),
  @cphone nvarchar(100),
  @amounts nvarchar(100),
  @cartnumber nvarchar(100)
as
  Declare @id int
  BEGIN TRANSACTION
    insert into Orders(Order_Country,Order_Adress,Order_UserName,Order_PostID,Cells,Order_Phone,Total_pay,CartNumber,IsPay)
      values (@country,@adds,@ynames,@pids,@cellp,@cphone,@amounts,@cartnumber,'0')
    Select @id=@@identity
    insert into Orders_Item (OrderNumber,ProductsID,Products_Color,Products_Price,Order_Qty,Item_Total)
      select @id,Carts_Item.ProductsID,Carts_Item.Products_Color,Carts_Item.Products_Price,Carts_Item.Item_Qty,Carts_Item.Total_Pay
      from Carts_Item where Carts_Item.CartNumber=@cartnumber
    delete Carts_Item where CartNumber=@cartnumber
    IF @@error <> 0 -- An error occurred 
    BEGIN
      ROLLBACK TRANSACTION
      RETURN 0
    END
    ELSE
    BEGIN
      COMMIT TRANSACTION
      RETURN @id  -- Successful execution 
  END


#region  Execute stored procedures 
SqlParameter[] param = new SqlParameter[]
{
   new SqlParameter("@country",country),
   new SqlParameter("@adds",adds),
   new SqlParameter("@ynames",ynames),
   new SqlParameter("@pids", pids),
   new SqlParameter("@cellp",cellp),
   new SqlParameter("@cphone", cphone),
   new SqlParameter("@amounts",amounts),
   new SqlParameter("@cartnumber",cartnumber),
   new SqlParameter("@return",SqlDbType.Int)
};
param[8].Direction = ParameterDirection.ReturnValue;
MSCL.SqlHelper.RunProcedure("AddOrderTran", param);
object obj = param[8].Value; // Accept the return value 
//string connStr = System.Configuration.ConfigurationManager.AppSettings["ConStr"].ToString();
//using (SqlConnection conn = new SqlConnection(connStr))
//{
//  conn.Open();
//  SqlCommand cmd = new SqlCommand("AddOrderTran", conn);
//  cmd.CommandType = CommandType.StoredProcedure;
//  SqlParameter para1 = new SqlParameter("@country", country);
//  para1.Direction = ParameterDirection.Input; // Parameter direction   Is an input parameter 
//  cmd.Parameters.Add(para1);
//  SqlParameter para2 = new SqlParameter("@adds", adds);
//  para2.Direction = ParameterDirection.Input;
//  cmd.Parameters.Add(para2);
//  SqlParameter para3 = new SqlParameter("@ynames", ynames);
//  para3.Direction = ParameterDirection.Input;
//  cmd.Parameters.Add(para3);
//  SqlParameter para4 = new SqlParameter("@pids", pids);
//  para4.Direction = ParameterDirection.Input;
//  cmd.Parameters.Add(para4);
//  SqlParameter para5 = new SqlParameter("@cellp", cellp);
//  para5.Direction = ParameterDirection.Input;
//  cmd.Parameters.Add(para5);
//  SqlParameter para6 = new SqlParameter("@cphone", cphone);
//  para6.Direction = ParameterDirection.Input;
//  cmd.Parameters.Add(para6);
//  SqlParameter para7 = new SqlParameter("@amounts", amounts);
//  para7.Direction = ParameterDirection.Input;
//  cmd.Parameters.Add(para7);
//  SqlParameter para8 = new SqlParameter("@cartnumber", cartnumber);
//  para8.Direction = ParameterDirection.Input;
//  cmd.Parameters.Add(para8);
//  SqlParameter paraReturn = new SqlParameter("@return", SqlDbType.Int);
//  paraReturn.Direction = ParameterDirection.ReturnValue; // Parameter direction   For the return parameter 
//  cmd.Parameters.Add(paraReturn);
//  cmd.ExecuteNonQuery();
//  object obj = paraReturn;
//  if (obj.ToString() == "0")
//  {
//    // Stored procedure execution failed 
//  }
//  else
//  {
//    // Success 
//  }
//}
//#endregion

The database in this paper uses sql, server and its own data Northwind

1. Stored procedures that return only single 1 recordsets


SqlConnection sqlconn = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand();
//  Settings sql Connect 
cmd.Connection = sqlconn;
//  If you execute a statement 
cmd.CommandText = "Categoriestest1";
//  Specify the execution statement as a stored procedure 
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter dp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
//  Padding dataset
dp.Fill(ds);
//  The following is the display effect 
GridView1.DataSource = ds;
GridView1.DataBind();

Stored procedure Categoriestest1


CREATE PROCEDURE Categoriestest1
 AS
 select *
 from Categories
 GO

2. Stored procedures without input and output


SqlConnection sqlconn = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = sqlconn;
cmd.CommandText = "Categoriestest2";
cmd.CommandType = CommandType.StoredProcedure;
sqlconn.Open();
//  Execute and display the number of affected rows 
Label1.Text = cmd.ExecuteNonQuery().ToString();
sqlconn.Close();

Stored procedure Categoriestest2


CREATE PROCEDURE Categoriestest2 AS
 insert into dbo.Categories
 (CategoryName,[Description],[Picture])
 values ('test1','test1',null)
 GO

3. Stored procedures with return values


SqlConnection sqlconn = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = sqlconn;
cmd.CommandText = "Categoriestest3";
cmd.CommandType = CommandType.StoredProcedure;
//  Create Parameters 
IDataParameter[] parameters = {
     new SqlParameter("rval", SqlDbType.Int,4)
   };
//  Set the parameter type to   Return value type 
parameters[0].Direction = ParameterDirection.ReturnValue;
//  Add parameters 
cmd.Parameters.Add(parameters[0]);
sqlconn.Open();
//  Execute the stored procedure and return the number of affected rows 
Label1.Text = cmd.ExecuteNonQuery().ToString();
sqlconn.Close();
//  Displays the number of affected rows and the return value 
Label1.Text += "-" + parameters[0].Value.ToString() ;

Stored procedure Categoriestest3


CREATE PROCEDURE Categoriestest3
 AS
 insert into dbo.Categories
 (CategoryName,[Description],[Picture])
 values ('test1','test1',null)
return @@rowcount
 GO

4. Stored procedures with input and output parameters


using (SqlConnection conn = new SqlConnection(connStr))
{
  try
  {
    SqlCommand cmd = new SqlCommand("GetNameById", conn);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@studentid", "09888888");    // Assign values to input parameters 
    SqlParameter parOutput =cmd.Parameters.Add("@studentname", SqlDbType.NVarChar, 50);    // Define output parameters 
    parOutput.Direction = ParameterDirection.Output;    // Parameter type is Output
    SqlParameter parReturn = new SqlParameter("@return", SqlDbType.Int);
    parReturn.Direction = ParameterDirection.ReturnValue;     // Parameter type is ReturnValue
    cmd.Parameters.Add(parReturn);
    conn.Open();
    cmd.ExecuteNonQuery();
    MessageBox.Show(parOutput.Value.ToString());  // Displays the value of the output parameter 
    MessageBox.Show(parReturn.Value.ToString());    // Display return value 
  }
  catch (System.Exception ex)
  {
    MessageBox.Show(ex.Message);
  }
}

0

Stored procedure Categoriestest4


using (SqlConnection conn = new SqlConnection(connStr))
{
  try
  {
    SqlCommand cmd = new SqlCommand("GetNameById", conn);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@studentid", "09888888");    // Assign values to input parameters 
    SqlParameter parOutput =cmd.Parameters.Add("@studentname", SqlDbType.NVarChar, 50);    // Define output parameters 
    parOutput.Direction = ParameterDirection.Output;    // Parameter type is Output
    SqlParameter parReturn = new SqlParameter("@return", SqlDbType.Int);
    parReturn.Direction = ParameterDirection.ReturnValue;     // Parameter type is ReturnValue
    cmd.Parameters.Add(parReturn);
    conn.Open();
    cmd.ExecuteNonQuery();
    MessageBox.Show(parOutput.Value.ToString());  // Displays the value of the output parameter 
    MessageBox.Show(parReturn.Value.ToString());    // Display return value 
  }
  catch (System.Exception ex)
  {
    MessageBox.Show(ex.Message);
  }
}

1

5. Stored procedures with return values, input parameters, and output parameters


using (SqlConnection conn = new SqlConnection(connStr))
{
  try
  {
    SqlCommand cmd = new SqlCommand("GetNameById", conn);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@studentid", "09888888");    // Assign values to input parameters 
    SqlParameter parOutput =cmd.Parameters.Add("@studentname", SqlDbType.NVarChar, 50);    // Define output parameters 
    parOutput.Direction = ParameterDirection.Output;    // Parameter type is Output
    SqlParameter parReturn = new SqlParameter("@return", SqlDbType.Int);
    parReturn.Direction = ParameterDirection.ReturnValue;     // Parameter type is ReturnValue
    cmd.Parameters.Add(parReturn);
    conn.Open();
    cmd.ExecuteNonQuery();
    MessageBox.Show(parOutput.Value.ToString());  // Displays the value of the output parameter 
    MessageBox.Show(parReturn.Value.ToString());    // Display return value 
  }
  catch (System.Exception ex)
  {
    MessageBox.Show(ex.Message);
  }
}

2

Stored procedure Categoriestest5


CREATE PROCEDURE Categoriestest5
 @id int output,
 @CategoryName nvarchar(15)
 AS
 insert into dbo.Categories
 (CategoryName,[Description],[Picture])
 values (@CategoryName,'test1',null)
set @id = @@IDENTITY
return @@rowcount
 GO

6. Stored procedures that return both parameters and recordsets


using (SqlConnection conn = new SqlConnection(connStr))
{
  try
  {
    SqlCommand cmd = new SqlCommand("GetNameById", conn);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@studentid", "09888888");    // Assign values to input parameters 
    SqlParameter parOutput =cmd.Parameters.Add("@studentname", SqlDbType.NVarChar, 50);    // Define output parameters 
    parOutput.Direction = ParameterDirection.Output;    // Parameter type is Output
    SqlParameter parReturn = new SqlParameter("@return", SqlDbType.Int);
    parReturn.Direction = ParameterDirection.ReturnValue;     // Parameter type is ReturnValue
    cmd.Parameters.Add(parReturn);
    conn.Open();
    cmd.ExecuteNonQuery();
    MessageBox.Show(parOutput.Value.ToString());  // Displays the value of the output parameter 
    MessageBox.Show(parReturn.Value.ToString());    // Display return value 
  }
  catch (System.Exception ex)
  {
    MessageBox.Show(ex.Message);
  }
}

4

Stored procedure Categoriestest6


using (SqlConnection conn = new SqlConnection(connStr))
{
  try
  {
    SqlCommand cmd = new SqlCommand("GetNameById", conn);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@studentid", "09888888");    // Assign values to input parameters 
    SqlParameter parOutput =cmd.Parameters.Add("@studentname", SqlDbType.NVarChar, 50);    // Define output parameters 
    parOutput.Direction = ParameterDirection.Output;    // Parameter type is Output
    SqlParameter parReturn = new SqlParameter("@return", SqlDbType.Int);
    parReturn.Direction = ParameterDirection.ReturnValue;     // Parameter type is ReturnValue
    cmd.Parameters.Add(parReturn);
    conn.Open();
    cmd.ExecuteNonQuery();
    MessageBox.Show(parOutput.Value.ToString());  // Displays the value of the output parameter 
    MessageBox.Show(parReturn.Value.ToString());    // Display return value 
  }
  catch (System.Exception ex)
  {
    MessageBox.Show(ex.Message);
  }
}

5

7. Stored procedures that return multiple recordsets


using (SqlConnection conn = new SqlConnection(connStr))
{
  try
  {
    SqlCommand cmd = new SqlCommand("GetNameById", conn);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@studentid", "09888888");    // Assign values to input parameters 
    SqlParameter parOutput =cmd.Parameters.Add("@studentname", SqlDbType.NVarChar, 50);    // Define output parameters 
    parOutput.Direction = ParameterDirection.Output;    // Parameter type is Output
    SqlParameter parReturn = new SqlParameter("@return", SqlDbType.Int);
    parReturn.Direction = ParameterDirection.ReturnValue;     // Parameter type is ReturnValue
    cmd.Parameters.Add(parReturn);
    conn.Open();
    cmd.ExecuteNonQuery();
    MessageBox.Show(parOutput.Value.ToString());  // Displays the value of the output parameter 
    MessageBox.Show(parReturn.Value.ToString());    // Display return value 
  }
  catch (System.Exception ex)
  {
    MessageBox.Show(ex.Message);
  }
}

6

Stored procedure Categoriestest7


using (SqlConnection conn = new SqlConnection(connStr))
{
  try
  {
    SqlCommand cmd = new SqlCommand("GetNameById", conn);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@studentid", "09888888");    // Assign values to input parameters 
    SqlParameter parOutput =cmd.Parameters.Add("@studentname", SqlDbType.NVarChar, 50);    // Define output parameters 
    parOutput.Direction = ParameterDirection.Output;    // Parameter type is Output
    SqlParameter parReturn = new SqlParameter("@return", SqlDbType.Int);
    parReturn.Direction = ParameterDirection.ReturnValue;     // Parameter type is ReturnValue
    cmd.Parameters.Add(parReturn);
    conn.Open();
    cmd.ExecuteNonQuery();
    MessageBox.Show(parOutput.Value.ToString());  // Displays the value of the output parameter 
    MessageBox.Show(parReturn.Value.ToString());    // Display return value 
  }
  catch (System.Exception ex)
  {
    MessageBox.Show(ex.Message);
  }
}

7

For more readers interested in C # related content, please check out the topics on this site: "C # Common Control Usage Tutorial", "WinForm Control Usage Summary", "C # Data Structure and Algorithm Tutorial", "C # Object-Oriented Programming Introduction Tutorial" and "C # Programming Thread Use Skills Summary"

I hope this article is helpful to everyone's C # programming.


Related articles: