I want to Write a function that returns the Products brought in a given month.
I tried this
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;
this giving me error. how can i pass month to pl/sql function and retrieve the data.
Pass in a date ('01-MAY-2003') and use date functions to make it work:
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 );
Using TRUNC(x, 'MM')
on the input month means you can pass in any date at teh query will run from the first day of the month.
Alternatively, you could use the LAST_DAY()
function which returns the start of the last day of the input month. You'd have to watch out for time values, since the Oracle DATE datatype can include both date and time.
I think that what you need is only to compare the month from the purchase_date column with the month on the param of the function...
I would do it this way
cursor cur
is
select *
from products
where TO_CHAR(purchase_date,'MM') >= TO_CHAR(mymonth, 'MM')
If you want to include also the year, you could use 'RRRRMM' as a param of TO_CHAR, instead of 'MM'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.