C#获取存储过程的 Return返回值和Output输出参数值

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#获取存储过程的 Return返回值和Output输出参数值相关的知识,希望对你有一定的参考价值。

一、不用SQLHelper.cs等帮助类

1.获取Return返回值
 程序代码
 存储过程
Create PROCEDURE mysql
  @a int,
  @b int
AS
  return @a + @b
GO
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ToString());
conn.Open();
SqlCommand MyCommand = new SqlCommand("MYSQL", conn);
MyCommand.CommandType = CommandType.StoredProcedure;
MyCommand.Parameters.Add(new SqlParameter("@a", SqlDbType.Int));
MyCommand.Parameters["@a"].Value = 10;
MyCommand.Parameters.Add(new SqlParameter("@b", SqlDbType.Int));
MyCommand.Parameters["@b"].Value = 20;
MyCommand.Parameters.Add(new SqlParameter("@return", SqlDbType.Int));
MyCommand.Parameters["@return"].Direction = ParameterDirection.ReturnValue;
MyCommand.ExecuteNonQuery();
Response.Write(MyCommand.Parameters["@return"].Value.ToString());

2.获取Output输出参数值
 程序代码
 存储过程
Create PROCEDURE MYSQL
   @a int,
   @b int,
   @c int output
AS
   Set @c = @a + @b
GO
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ToString());
conn.Open();
SqlCommand MyCommand = new SqlCommand("MYSQL", conn);
MyCommand.CommandType = CommandType.StoredProcedure;
MyCommand.Parameters.Add(new SqlParameter("@a", SqlDbType.Int));
MyCommand.Parameters["@a"].Value = 20;
MyCommand.Parameters.Add(new SqlParameter("@b", SqlDbType.Int));
MyCommand.Parameters["@b"].Value = 20;
MyCommand.Parameters.Add(new SqlParameter("@c", SqlDbType.Int));
MyCommand.Parameters["@c"].Direction = ParameterDirection.Output;
MyCommand.ExecuteNonQuery();
Response.Write(MyCommand.Parameters["@c"].Value.ToString());
 
---------------------------------------------------------------------------------------------------------------
以下代码转自网络:
C#接收存储过程返回值:
     public static int User_Add(User us)
     {
         int iRet;
         SqlConnection conn = new SqlConnection(Conn_Str);
         SqlCommand cmd = new SqlCommand("User_Add", conn);
         cmd.CommandType = CommandType.StoredProcedure;
         cmd.Parameters.AddWithValue("@UName", us.UName);
         cmd.Parameters.AddWithValue("@UPass", us.UPass);
         cmd.Parameters.AddWithValue("@PassQuestion", us.PassQuestion);
         cmd.Parameters.AddWithValue("@PassKey", us.PassKey);
         cmd.Parameters.AddWithValue("@Email", us.Email);
         cmd.Parameters.AddWithValue("@RName", us.RName);
         cmd.Parameters.AddWithValue("@Area", us.Area);
         cmd.Parameters.AddWithValue("@Address", us.Address);
         cmd.Parameters.AddWithValue("@ZipCodes", us.ZipCodes);
         cmd.Parameters.AddWithValue("@Phone", us.Phone);
         cmd.Parameters.AddWithValue("@QQ", us.QQ);
         cmd.Parameters.Add("@RETURN_VALUE", "").Direction = ParameterDirection.ReturnValue;      
         try
         {
             conn.Open();
             cmd.ExecuteNonQuery();
             iRet = (int)cmd.Parameters["@RETURN_VALUE"].Value;
         }
         catch (SqlException ex)
         {
             throw ex;
         }
         finally
         {
             conn.Close();
         }
         return iRet;
     }
C#接收存储过程输出参数:
    public static decimal Cart_UserAmount(int UID)
    {
        decimal iRet;
        SqlConnection conn = new SqlConnection(Conn_Str);
        SqlCommand cmd = new SqlCommand("Cart_UserAmount", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@UID", UID);
        cmd.Parameters.Add("@Amount", SqlDbType.Decimal).Direction=ParameterDirection.Output;
        try
        {
            conn.Open();
            cmd.ExecuteNonQuery();
            iRet = (decimal)cmd.Parameters["@Amount"].Value;
        }
        catch (SqlException ex)
        {
            throw ex;
        }

二、用SQLHelper.cs等帮助类,其思想一样

如:(贴出部分代码)

string readercode = txt_reader_code.Text;
string bookcode = txt_book_code.Text;
decimal money = Convert.ToDecimal(txt_price.Text);
DateTime borrowDate = Convert.ToDateTime(DateTime.Now.ToShortDateString());
 DataTable table = new DBUtility.bookType().GetTableByBookBarCode(bookcode);
double borrowday;
double getday = 0d;
if (table != null && table.Rows.Count > 0)
{
    if (double.TryParse(table.Rows[0]["borrowday"].ToString(), out borrowday))
    {
         getday = borrowday;
    }
}
else
{
     Pub.Util.AlertPostBack(Page, "得到图书借阅天数失败");
     return;
}
DateTime returnDate = Convert.ToDateTime(DateTime.Now.AddDays(getday).ToShortDateString());
string readerName = txt_name.Text.Trim();
string bookName = txt_book_name.Text.Trim();

SqlParameter[] parameters = {
           new SqlParameter("@readerBarCode",SqlDbType.VarChar),
           new SqlParameter("@bookBarCode",SqlDbType.VarChar),
           new SqlParameter("@hire",SqlDbType.Money),
           new SqlParameter("@borrowDate",SqlDbType.DateTime),
           new SqlParameter("@returnDate",SqlDbType.DateTime),
           new SqlParameter("@readerName",SqlDbType.VarChar),
           new SqlParameter("@bookName",SqlDbType.VarChar),
           new SqlParameter("@return",SqlDbType.Int)           //添加一个返回参数
       };
parameters[0].Value = readercode;
parameters[1].Value = bookcode;
parameters[2].Value = money;
parameters[3].Value = borrowDate;
parameters[4].Value = returnDate;
parameters[5].Value = readerName;
parameters[6].Value = bookName;
parameters[7].Direction = ParameterDirection.ReturnValue; //声明此参数是返回类型


DBUtility.SQLHelper.ExecuteNonQuery(DBUtility.SQLHelper.BookConn, CommandType.StoredProcedure, "p_bookBorrow", parameters);


int num = Convert.ToInt32(parameters[7].Value.ToString());//提取存储过程返回参数的值,成功为0,不成功为-1

if (num == 0)
{     Pub.Util.AlertPostBack(Page, "借阅成功");
}
else
   Pub.Util.AlertPostBack(Page, "借阅失败");

 

 

 

存储过程

 

create procedure p_bookBorrow(@readerBarCode varchar(30),@bookBarCode varchar(30),@hire money,@borrowDate datetime,@returnDate datetime,@bookName varchar(30),@readerName varchar(20))
as
begin tran
insert into t_reader_book values(@readerBarCode,@bookBarCode,@borrowDate,@returnDate,@bookName,@readerName)
if(@@error<>0)
begin
  rollback tran
  return -1
end
update t_readerinfo set borrownum=borrownum+1,[money]=[money][email protected] where readerBarCode = @readerBarCode
if(@@error<>0)
begin
  rollback tran
  return -1
end
update t_bookinfo set stock=stock-1 where bookBarCode [email protected]
if(@@error<>0)
begin
  rollback tran
  return -1
end
insert into logs values(getDate(),‘条形码号为:[email protected]+‘的读者,借阅了图书编号为:[email protected]+‘的书籍‘)
if(@@error<>0)
begin
  rollback tran
  return -1
end
commit tran
if(@@error<>0)
  return -1
else
  return 0

GO

 

以上是关于C#获取存储过程的 Return返回值和Output输出参数值的主要内容,如果未能解决你的问题,请参考以下文章

c#调用oracle存储过程,返回2个值

C# 调用存储过程操作 OUTPUT参数和Return返回值

获取存储过程返回值的几种方式

从 C# 中的存储过程中获取返回值

C# 获取 oracle 存储过程的 返回值

当我们在 plsql 中动态传递列名的值和相应的列值时获取整行的存储过程