Note that there are some explanatory texts on larger screens.

plurals
  1. POOracle stored proc - dynamically generate select statement based on optional params
    primarykey
    data
    text
    <pre><code>create or replace PROCEDURE get_txn_by_account_id( p_ACCOUNT_ID IN txn.ACCOUNT_ID%TYPE DEFAULT NULL ) IS BEGIN FOR x IN (SELECT * FROM txn where account_id=p_ACCOUNT_ID) LOOP dbms_output.put_line(x.txn_ID || ', ' || x.txn_VER_NB); END LOOP; END get_txn_by_account_id; </code></pre> <p>my stored procedure issues a select based on one input as search criteria and outputs the search results. My input is ACCOUNT_ID. I'd like to add 4 additional input params (param_a, param_b, param_c, param_d) - at least two of which will be optional. </p> <p>So I'll probably change my stored proc declaration like</p> <pre><code>PROCEDURE get_txn_by_account_id( p_ACCOUNT_ID IN txn.ACCOUNT_ID%TYPE DEFAULT NULL, p_PARAM_A IN txn.PARAM_A%TYPE DEFAULT NULL, p_PARAM_B IN txn.PARAM_B%TYPE DEFAULT NULL, p_PARAM_C IN txn.PARAM_C%TYPE DEFAULT NULL, p_PARAM_D IN txn.PARAM_D%TYPE DEFAULT NULL ) </code></pre> <p>So my SELECT may have varying number of query params based on what optional params are passed to the stored proc.</p> <p>For instance,</p> <pre><code>FOR x IN (SELECT * FROM txn where account_id=p_ACCOUNT_ID, param_a=p_PARAM_A, param_b=p_PARAM_B, param_c=p_PARAM_C, param_d=p_PARAM_D) FOR x IN (SELECT * FROM txn where account_id=p_ACCOUNT_ID, param_a=p_PARAM_A, param_c=p_PARAM_C, param_d=p_PARAM_D) FOR x IN (SELECT * FROM txn where account_id=p_ACCOUNT_ID, param_a=p_PARAM_A, param_b=p_PARAM_B, param_d=p_PARAM_D) </code></pre> <p>or</p> <pre><code>FOR x IN (SELECT * FROM txn where account_id=p_ACCOUNT_ID, param_a=p_PARAM_A, param_b=p_PARAM_B) </code></pre> <p>etc.</p> <p>I'm having trouble with - how to code my stored proc so that the SELECT statement changes based on what optional params are passed to the stored proc - perhaps a string builder that builds a query statement based on optional params passed in to the proc, and then use the resulting string in the query? I'm not sure if this is even possible. Surely this is a common problem - anyone have any suggestions? Thanks!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload