Oracle stored process parameters combined with dynamic cursor splicing sql

premise

Today in the business of writing stored procedures, you need to splice AND conditions, and the presence of up to 10 permutations based on business logic requires that, in the past when only twenty-three kinds of permutations and combinations, I direct use of PL / SQL IF statement branches judgment, clear and concise.
Since many permutations and combinations, and sql statement is also consistent, we want to sql extracted, as a global sql, then by splicing WHERE statement. Thus, a case where a sql permutations resolved, the code redundancy stored procedure also greatly reduced.

problem

Cursor parameters, namely: [Parameter Name] OUT sys_refcursor
cursor basic use, PL / SQL as follows:

    OPEN myCur FOR
    SELECT * FROM person;

That if you need to use cursors in a stored procedure output combined with dynamic sql stitching, how?

Solution

Examples are as follows:

DECLARE
   p_person_id varchar(255);
   p_person_phone varchar(255);
   SQL_Text varchar2(32760) := 'SELECT * FROM person WHERE 1 = 1 ';
   myCur sys_refcursor;
BEGIN
   IF p_person_id IS NOT NULL THEN 
       SQL_Text := SQL_Text || 'AND person_id = '' ' || p_person_id || ''' ';
   END IF;
   IF p_person_phone IS NOT NULL THEN 
       SQL_Text := SQL_Text || 'AND person_phone = '' ' || p_person_phone || ''' ';
   END IF;
   dbms_output.put_line(SQL_Text);
   OPEN myCur FOR SQL_Text;
END;

Precautions:

  • When the cursor parameter, OPEN-FOR can be directly used instead EXECUTE IMMEDIATE
  • Dynamic SQL (SQL_Text) length is limited to ensure that their dynamic SQL splice after completion of length does not overflow (online there are other ways to support a longer length, please check yourself)
  • WHERE 1 = 1 for facilitating connection conditions, and appropriate application of attention spaces
  • Use print output statements about the development of dynamic SQL, see the statement is correct

Guess you like

Origin www.cnblogs.com/zhuang229/p/12381294.html