Home > Net >  How to create a function that returns a query based on user input in PL/SQL?
How to create a function that returns a query based on user input in PL/SQL?

Time:03-19

I am a beginner at PL/SQL and trying to learn how to write functions with input parameters and return values. However, I am having a hard time finding any information on how to return multiple table rows in a function.

I want to create a function that allows the user to input a string, and then my function will return a query with a where clause based on the input.

For example,

the user can enter the input "January" when calling my function.

Then, when my function is running, I want to basically do:

return select * from DataTable where month = "January"

Is there any way to do this simply in PL/SQL? I would really appreciate the help!

CodePudding user response:

I assume you want your function to return an actual query, not the result of running the query. In that case you are looking for a function that returns a string. In this case a simple string (varchar2) replacement. Try: (see demo)

create or replace function get_month_query( month_name_in varchar2) 
  return varchar2 
is
    k_base_query constant varchar2(60) := 
        'select * from datatable where month = ''parm_month'''; 
begin    
    return (replace( k_base_query, 'parm_month', month_name_in) ); 
end get_month_query; 

Note: There are many other ways to accomplish this, it is just my style.

CodePudding user response:

You can try:

CREATE OR REPLACE FUNCTION compose_query(p_month VARCHAR2)
  RETURN VARCHAR2
IS
 l_month DATE;
BEGIN
  BEGIN
    SELECT to_date(p_month,'Month')
      INTO l_month
      FROM dual;
  EXCEPTION WHEN OTHERS  
    THEN 
      RETURN 'ERROR';
  END;
  RETURN 'select * from datatable where month = '||''''||p_month||''';';
END;

not a great idea in general, but a small insurance at least.

CodePudding user response:

Hope this helps:

-for this table:

create table datatable (ID number, month date);

-u need to create these 2 types:

create or replace type o_type as object (a number, b date);
create or replace type t_type is table of o_type;

-and here is the function:

create or replace function f_function (p_month in varchar2)
return t_type PIPELINED is
v_month date:=to_date(p_month,'Month');
begin
    for i in (select * from DataTable where month=v_month) loop
        pipe row (o_type(i.id,i.month));
        end loop;
        RETURN;
end;

test:

insert into datatable values(1,to_date('January','Month'));
insert into datatable values(2,to_date('January','Month'));
insert into datatable values(3,to_date('January','Month'));
insert into datatable values(4,to_date('October','Month'));
insert into datatable values(5,to_date('July','Month'));


select * from table(f_function('January'));

Result:

1   01.01.2022
2   01.01.2022
3   01.01.2022
  • Related