How to pass schema name as parameter in stored procedure

可紊 提交于 2019-12-11 05:25:20

问题


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.


回答1:


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.




回答2:


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




回答3:


You need use Dynamic SQL, there are tons of material on Internet. e.g. 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;
/


来源:https://stackoverflow.com/questions/12108085/how-to-pass-schema-name-as-parameter-in-stored-procedure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!