一、创建存储过程
--创建带有输出参数的存储过程 create procedure pro_readerlist3 @unit varchar(40) = '%', @minbookcount int =0, @avg_total float output, @avg_select float output as select R.readerid,R.readername,R.unit,R.bookcount,Count(B.reader) as 'borrowbooks' from ReaderInfo as R left outer join BookInfo as B on R.readerid=B.reader where R.unit like @unit and R.bookcount >=@minbookcount group by R.readerid,R.readername,R.unit,R.bookcount order by R.bookcount set @avg_total=(select avg(cast(bookcount as float)) from ReaderInfo) set @avg_select=(select avg(cast(bookcount as float)) from ReaderInfo where unit like @unit and bookcount >=@minbookcount)二 、在C#工程中创建链接数据库
SqlConnection conn = new SqlConnection(sqlConnStr); SqlCommand comm = new SqlCommand("dbo.pro_readerlist3", conn); comm.CommandType = System.Data.CommandType.StoredProcedure; comm.Parameters.Add("@unit", SqlDbType.VarChar).Value = "Computer"; comm.Parameters.Add("@minbookcount", SqlDbType.Int).Value = 0; comm.Parameters.Add("@avg_total", SqlDbType.VarChar,100).Direction = ParameterDirection.Output; comm.Parameters.Add("@avg_select", SqlDbType.VarChar,100).Direction = ParameterDirection.Output; DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(comm); da.Fill(ds); string rtnstr = comm.Parameters["@avg_total"].Value.ToString(); Console.WriteLine(rtnstr);
需要注意的是在添加output的参数时需要指定长度。