是否可以使用动态同义词参数化存储过程中查询中使用的模式和表名?
我们尝试的是
我们尝试这种方法的原因是因为要执行的查询是数百行的合并语句,不适合动态SQL。
答案 0 :(得分:3)
当您使用Invoker Rights进行手术时,也许您可以解决您的问题。看看这个例子:
CREATE USER SCOTT_1 IDENTIFIED BY "tiger";
GRANT UNLIMITED TABLESPACE TO SCOTT_1;
CREATE USER SCOTT_2 IDENTIFIED BY "tiger";
GRANT UNLIMITED TABLESPACE TO SCOTT_2;
CREATE TABLE SCOTT_1.EMP (EMP_NAME VARCHAR2(30));
CREATE TABLE SCOTT_2.EMP (EMP_NAME VARCHAR2(30));
INSERT INTO SCOTT_1.EMP VALUES ('Schema 1');
INSERT INTO SCOTT_2.EMP VALUES ('Schema 2');
COMMIT;
CREATE SYNONYM EMP FOR SCOTT_1.EMP; -- Just needed to compile the procedure
CREATE OR REPLACE FUNCTION GetSchema(p_schema IN VARCHAR2) RETURN VARCHAR2
AUTHID CURRENT_USER
AS
res VARCHAR2(30);
BEGIN
EXECUTE IMMEDIATE 'ALTER SESSION SET CURRENT_SCHEMA = ' || p_schema;
SELECT EMP_NAME
INTO res
FROM EMP;
-- Just switch back to own schema to avoid unexpected behaviors
EXECUTE IMMEDIATE 'ALTER SESSION SET CURRENT_SCHEMA = '||USER;
RETURN res;
END;
/
SELECT GetSchema('SCOTT_1') FROM dual;
GETSCHEMA('SCOTT_1')
---------------------------------
Schema 1
1 row selected.
SELECT GetSchema('SCOTT_2') FROM dual;
GETSCHEMA('SCOTT_2')
---------------------------------
Schema 2
1 row selected.