需求: 存储过程完成一年创建一个表
实现代码如下:
CREATE OR REPLACE procedure TEST123456 AS suffix_year VARCHAR(5); TABLENAME VARCHAR(40); BEGIN SELECT TO_CHAR(SYSDATE,'yyyy') INTO suffix_year FROM DUAL; TABLENAME:='TEST'||suffix_year; DBMS_OUTPUT.put_line(suffix_year); CREATE TABLE TABLENAME||'123' AS select * from TEST t WHERE 1=2; -- EXCEPTION -- WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.put_line('异常'); END;
上面的方法一直编译不过去,因为我的表名称是一个变量,后来通过查阅各种资料了解到 可以用execute immediate 来实现!
新实现代码如下:
CREATE OR REPLACE procedure TEST123456 AS suffix_year VARCHAR(5); TABLENAME VARCHAR(40); BEGIN SELECT TO_CHAR(SYSDATE,'yyyy') INTO suffix_year FROM DUAL; TABLENAME:='TEST'||suffix_year; DBMS_OUTPUT.put_line(suffix_year); --CREATE TABLE TABLENAME||'123' AS select * from ZP_SCAN_ORDER t WHERE 1=2; execute immediate 'CREATE TABLE '||TABLENAME || ' AS select * from ZP_SCAN_ORDER t WHERE 1=2 '; -- EXCEPTION -- WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.put_line('异常'); END;上面方法编译算是成功了,但是在执行的时候发现 执行错误,提示是权限不足,然而我们把
execute immediate 'CREATE TABLE '||TABLENAME || ' AS select * from ZP_SCAN_ORDER t WHERE 1=2 ';直接在plsql中执行是没有问题的!
这个问题怎么解决呢?
既然提示权限不足,那我就赋值权限给当前用户user1,以sys用户登录 执行如下sql:
GRANT CREATE ANY TABLE TO user1
再次执行存储过程,没有问题,成功!原文链接:https://www.f2er.com/oracle/211505.html