刚学存储过程,遇到下面的问题:create procedure RPT(@user_id varchar(30),@date1 date,@date2 date,@product_id varchar(100))
as 
select 
date_drv.date1 as user_time, 
sum(pv) as pv,
sum(uv) as uv
from date_drv 
left join reprot a 
ON date_drv.date1=a.user_time and a.user_id=@user_id 
where date_drv.date1  between @date1 and @date2
and product_id=@product_id 
group by date_drv.date1,a.product_id order by 1;
在上面的存储过程中,user_time 有时候需要传入date_drv.date1 ,有时候需要传入date_drv.month1 ,这样的存储过程怎么写呢?谢谢!

解决方案 »

  1.   

    试试动态SQL,参数做判断去拼接SQL查询字符串,然后执行输出!
      

  2.   

    加一个参数,利用它,用case 来判断输出哪一个.
      

  3.   

    select (case when flg=1 then date_drv.date1 else date_drv.month1 end) ....
      

  4.   


    create procedure RPT
    (@user_id varchar(30),@date1 date,@date2 date,@product_id varchar(100),@flag int)
    as  
    select  
    (case when @flag = 1 then date_drv.date1 else date_drv.month1 end) as user_time,  
    sum(pv) as pv,
    sum(uv) as uv
    from date_drv  
    left join reprot a  
    ON (case when @flag = 1 then date_drv.date1 else date_drv.month1 end)=a.user_time 
      and a.user_id=@user_id  
    where (case when @flag = 1 then date_drv.date1 else date_drv.month1 end) between @date1 and @date2
    and product_id=@product_id  
    group by (case when @flag = 1 then date_drv.date1 else date_drv.month1 end),a.product_id order by 1;貌似这样也可以!
      

  5.   

    非常感谢二位的回复。AcHerat提供的方法还是会报错:case when 语句选择变量的时候,数据类型转换的错误。date1 数据类型是date ,month1 类型是 int.
    如果在外面加  if...begin ...end 
                 else if...begin...end 
    这样可以得到正确结果。可是如果参数传入很多的话,比如既有按月(month1),又有按日(date1),又有按周(week1)等等进行数据汇总的话,相当于同一段程序写了很多遍,代码太长了...不知道有没有好的解决方法?