简体   繁体   中英

How to pass schema name as parameter in stored procedure

I need to pass a schema name as a parameter to a stored procedure. But I end up with error ORA00942: table or view does not exist . I googled a lot but didn't find any solution.

Actually in our application we are writing a Stored procedure (SP) in One schema and referring the same SP for all other schemas.

Consider I have to find the stock of an item in a different schema (1 schema for 1 client). Then

select * from abc.stock_table where itemid=xxx;

In this query I want to replace abc with different schema names.

You need use Dynamic SQL, there are tons of material on Internet. eg on oracle website

CREATE OR REPLACE PROCEDURE query_invoice(
       month VARCHAR2, 
       year VARCHAR2) IS
    TYPE cur_typ IS REF CURSOR;
    c cur_typ;
    query_str VARCHAR2(200);
    inv_num NUMBER;
    inv_cust VARCHAR2(20);
    inv_amt NUMBER;
BEGIN
    query_str := 'SELECT num, cust, amt FROM inv_' || month ||'_'|| year 
      || ' WHERE invnum = :id';
    OPEN c FOR query_str USING inv_num;
    LOOP
        FETCH c INTO inv_num, inv_cust, inv_amt;
        EXIT WHEN c%NOTFOUND;
        -- process row here
    END LOOP;
    CLOSE c;
END;
/

It's imposible to change scheme in compiled PLSQL code on the fly. You should use dynamic SQL instead. http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/dynamic.htm But you must understand that this option has side effect - each time when you call dynamic sql it compiles again. So it's slower and more risky.

Create public synonym for your object from different schema. Grant privilege on it.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM