Oracle PL SQL,动态同义词可行(参数化模式/表名)?

时间:2015-10-27 13:33:35

标签: oracle stored-procedures dynamic plsql synonym

是否可以使用动态同义词参数化存储过程中查询中使用的模式和表名?

我们尝试的是

  1. 在名称/值对表中设置参数
  2. 在运行时读取这些参数以确定模式(和表名称),因为目标会根据模式而变化 应用
  3. 删除任何现有的同义词并重新创建架构和表格
  4. 引用查询中的同义词
  5. 我们尝试这种方法的原因是因为要执行的查询是数百行的合并语句,不适合动态SQL。

1 个答案:

答案 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.