C#調用存儲過程 之返回值與輸出參數

首先定義存儲過程如下:(sqlserver 2008)

use studb2008
go
create procedure proc_test
@num int=-1 output
as
  set @num=10 --輸出參數
  return 2  --返回值
  go

 

然後在vs中寫如下c#代碼:

namespace StoreProcedureTest
{
    class Program
    {
        static void Main(string[] args)
        {

            string s = @"Data Source=.\sql2008express;Initial Catalog=studb2008;User ID=sa;Password=sa";
            SqlConnection con = new SqlConnection(s);
            SqlCommand command = new SqlCommand();
            command.Connection = con;
            command.CommandText = "proc_test"; //proc_test爲存儲過程的名字
           command.CommandType = CommandType.StoredProcedure; //設置執行的類型
            SqlParameter para = new SqlParameter("@a",SqlDbType.Int);//任意定義一個變量,來接收返回值參數
            para.Direction = ParameterDirection.ReturnValue;   //注意這裏1 表示接收返回值
            command.Parameters.Add(para);
            SqlParameter para2 = new SqlParameter("@num", SqlDbType.Int); //第二個變量來接收存儲過程的輸出參數
            para2.Direction = ParameterDirection.Output;   //注意這裏2 表示接收輸出值
          command.Parameters.Add(para2);
            con.Open();
            command.ExecuteNonQuery();
            int n = (int)command.Parameters["@a"].Value;
            int n2 = (int)command.Parameters["@num"].Value;
            Console.WriteLine(“n:”+n+":n2="+n2); //分別輸出返回值和輸出參數的值。分別是2和10
            Console.ReadLine();
            con.Close();

        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章