将月份传递给pl / sql函数?

时间:2011-11-14 12:52:17

标签: sql oracle plsql date-arithmetic

我想写一个函数来返回给定月份带来的产品。

我试过这个

 create or replace 
 function myfun(mymonth date) 
    return date
 is  
    cursor cur 
    is 
       select * 
         from products 
        where purchase_date=mymonth;
 begin
    for i in cur
    loop
       dbms_output.put_line(i.product_id || ', ' || 
                            i.description || ', ' || 
                            i.product_name || ', ' || 
                            i.quantity || ', ' || 
                            i.price || ', ' || 
                            i.purchase_date);
    end loop;
    return 1;
 end;  

这给了我错误。 我怎样才能将月份传递给pl / sql函数并检索数据。

2 个答案:

答案 0 :(得分:1)

传递日期('01 -MAY-2003')并使用日期功能使其有效:

create or replace 
 function myfun(mymonth date) 
    return date
 is  
    cursor cur 
    is 
       select * 
         from products 
        where purchase_date >= TRUNC(mymonth, 'MM')
          and purchase_date < ADD_MONTHS( TRUNC(mymonth,'MM') , 1 );

在输入月份上使用TRUNC(x, 'MM')表示您可以传入任何日期,查询将从该月的第一天开始运行。

或者,您可以使用LAST_DAY()函数返回输入月份最后一天的开头。您必须注意时间值,因为Oracle DATE数据类型可以包含日期和时间。

答案 1 :(得分:0)

我认为你需要的只是将purchase_date列中的月份与函数param上的月份进行比较......

我会这样做

cursor cur 
is 
   select * 
     from products 
    where TO_CHAR(purchase_date,'MM') >= TO_CHAR(mymonth, 'MM')

如果你想包括年份,可以使用'RRRRMM'作为TO_CHAR的参数,而不是'MM'