溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

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

發(fā)布時間:2020-06-14 18:41:23 來源:網(wǎng)絡 閱讀:831 作者:atixujie 欄目:編程語言

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

use studb2008
go
create procedure proc_test
@num int=-1 output
as
  set @num=10 --輸出參數(shù)
  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; //設置執(zhí)行的類型
            SqlParameter para = new SqlParameter("@a",SqlDbType.Int);//任意定義一個變量,來接收返回值參數(shù)
            para.Direction = ParameterDirection.ReturnValue;   //注意這里1 表示接收返回值
            command.Parameters.Add(para);
            SqlParameter para2 = new SqlParameter("@num", SqlDbType.Int); //第二個變量來接收存儲過程的輸出參數(shù)
            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); //分別輸出返回值和輸出參數(shù)的值。分別是2和10
            Console.ReadLine();
            con.Close();

        }
    }
}

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI