使用輸出參數,可以使儲存過程返回多個值.例如,查詢某表的信息,並希望返回表的記錄數,可以在儲存過程中使用輸出參數.
create procedure employeesproc
@empCount int output
as
select * from employees
select @empCount=count(*) from employees
go
在@empCount參數後面,加了output關鍵字,表示這是一個輸出參數.output是SQL Server數據庫定義的關鍵字.
SqlParameter對象的Direction屬性,這個屬性用來指定參數的類型.Direction屬性是ParameterDirection枚舉類型.
Input 指定參數是輸入參數
InputOutput 指定參數既能輸入,也能輸出
OutPut 指定參數是輸出參數
Return Value 指定參數表示如儲存過程,內置函數或用戶定義函數之類的操作返回值
其中Direction屬性的默認值是Input
myCommand.Parameters.add(“@empCount”,SqlDbType.Int);
myCommand.Parameter[“@empCount”].Direction=ParameterDirection.Output;
//創建數據儲存過程
create procedure elogin1_ws
@bumen nvarchar(25),
@empcount int output
as
--查詢滿足條件的記錄
select 部門名稱,工號,中文姓名,nt from elogin1
where 部門名稱=@bumen
--統計滿足條件的記錄數
select @empcount=count (*) from elogin1 where 部門名稱=@bumen
GO
//乘隙中調用儲存過程
private void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
{
//創建數據庫連接字符串
string connstr="server=10.64.2.80;user id=ieb;pwd=ieb;database=cust";
//創建Connection and Command對象
SqlConnection myconn=new SqlConnection(connstr);
SqlCommand mycommand=new SqlCommand("elogin1_ws",myconn);
//指定要執行的命令為儲存過程
mycommand.CommandType=CommandType.StoredProcedure;
//增加輸入參數,並賦值
mycommand.Parameters.Add("@bumen",SqlDbType.NVarChar,25);
mycommand.Parameters["@bumen"].Value =this.DropDownList1.SelectedItem.Text;
mycommand.Parameters["@bumen"].Direction=ParameterDirection.Input;
//增加輸出參數
mycommand.Parameters.Add("@empcount",SqlDbType.Int);
mycommand.Parameters["@empcount"].Direction=ParameterDirection.Output;
//創建DataAdapter對象填充數據
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter(mycommand);
da.Fill(ds,"elogin1");
//使用Label控件顯示輸出參數的輸出值
this.Label1.Text=mycommand.Parameters["@empcount"].Value.ToString();
//將返回的數據和DataGrid綁定顯示
this.DataGrid1.DataSource=ds.Tables["elogin1"];
this.DataGrid1.DataBind();
}