简单的存储过程编写与调用

如果程序有一段SQL需要重复用,而后台数据库是sqlserver或oracle则可以把这些SQL写成一个存储过程,这样使用起来方便而且减轻了网络流量,数据库执行起来更快些.
例:
 
create procedure get_class_count
@class_id int ,  /*定义一个参数类型是int*/
@start_date datetime=null,
/*"="的做用是设置该参数的默认值,这样在调用时可以不给此参数赋值*/
@end _date datetime=null
 
as /*代码段开始*/
if start_date is null
   select count(count_id) from class_count where count_class=@class_id
else
   select count(count_id from class_count where count_class=@class_id and count_date>=@start_date  and count_date <=@end_date
 
go
 
可以在C#中写一个函数,来调用这个存储过程
一个参数的调用函数
private int get_class_count(int c_id)
{
     getconnect gc=new getconnect();
     gc.openconn();
     SqlCommand cmd=new SqlCommand();
     cmd.CommandType=CommandType.StoredProcedure;
     cmd.CommandText="get_class_count";
     cmd.Parameters.Add(new SqlParameter("@class_id",SqlDbType.int));
     cmd.Parameters["@class_id"].Value=c_id;
     try
     {
          return(int.P***(cmd. ExecuteScalar().ToString()));
          
      }
     catch( Exception e)
     {
         System.Web.HttpContext.Current.Response.Wrtie (e.Message.ToString());
      }
      finally
      {
          gc.closeconn();
      }
}
 三个参数的调用函数
public int get_class_count(int id,string s_date,string e_date)
  {
   if (s_date==null || e_date==null)
   {
    return(0);
   }
   getconnect conn=new getconnect();
   if (conn.conn.State.ToString()=="Closed")
   {
    conn.openconn();
   }
   SqlCommand cmd=new SqlCommand();
   cmd.CommandType=CommandType.StoredProcedure;
   cmd.CommandText="get_class_count";
   cmd.Parameters.Add(new SqlParameter("@class_id",SqlDbType.Int));
   cmd.Parameters["@class_id"].Value=id;
   cmd.Parameters.Add(new SqlParameter("@start_date",SqlDbType.DateTime));
   cmd.Parameters["@start_date"].Value=s_date;
   cmd.Parameters.Add(new SqlParameter("@end_date",SqlDbType.DateTime));
   cmd.Parameters["@end_date"].Value=e_date;
   try
   {
    return(int.P***(cmd.ExecuteScalar().ToString()));
   }
   catch(Exception e)
   {
    System.Web.HttpContext.Current.Response.Write(e.Message.ToString());
    return(0);
   }
   finally
   {
    conn.closeconn();
   }
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值