Saturday 21 February 2015

Passing table name dynamically to a query

DECLARE
   v_amount    NUMBER;
   v_db_link   VARCHAR2 (200) := NULL;

   TYPE cur_typ IS REF CURSOR;

   c           cur_typ;
BEGIN
   SELECT db_link
     INTO v_db_link
     FROM dba_db_links
    WHERE db_link LIKE '%ASCP%';

   v_db_link := 'mtl_onhand_quantities_detail@' || v_db_link;
   DBMS_OUTPUT.put_line (v_db_link);

   OPEN c FOR    'SELECT NVL(SUM(PRIMARY_TRANSACTION_QUANTITY),0) X   FROM '
              || v_db_link;

   LOOP
      FETCH c
       INTO v_amount;

      EXIT WHEN c%NOTFOUND;
      DBMS_OUTPUT.put_line (v_amount);
   END LOOP;

   CLOSE c;
END;



Note : In this example, our requirement was to fetch name of the DB Link dynamically from table And then using the same into SELECT statement. Moreover, we can not directly use it into a formula column of a RDF report or FORM. For that we have to create a function into database with all the required parameters.