问题
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