Oracle PL / SQL如何将替换变量的结果重新分配给新变量?

时间:2014-08-20 20:31:35

标签: sql oracle variables plsql substitution

我在尝试将替换变量用于表名时遇到了一个小问题。当我使用QTR_END 31-DEC-2009日期运行以下代码时,我收到错误,因为它代替QUARTER = 4ACCYEAR = 2009,它会尝试创建一个名为table的表的:

"ZZ_PLANNING_DATA_TO_NUMBER(TO_CHAR(TO_DATE('&&QTR_END','DD-MM-YYYY'), 'Q'))QTO_NUMBER(EXTRACT (YEAR FROM TO_DATE('&&QTR_END','DD-MM-YYYY')))"

当然我正在尝试创建一个表"ZZ_PLANNING_DATA_4Q2009"

我不知道如何强制替换变量替换其执行值,而不是仅仅替换代码。 ?

ACCEPT QTR_END DATE PROMPT 'Enter the last day of the period you wish to run (i.e.: 30-JUN-2014).';

DEFINE QUARTER = TO_NUMBER(TO_CHAR(TO_DATE('&&QTR_END','DD-MM-YYYY'), 'Q'));
DEFINE ACCYEAR = TO_NUMBER(EXTRACT (YEAR FROM TO_DATE('&&QTR_END','DD-MM-YYYY')));

DEFINE BACKUP_TABLE_NAME = "ZZ_PLANNING_DATA_&&QUARTER.Q&&ACCYEAR";
CREATE TABLE &&BACKUP_TABLE_NAME COMPRESS NOLOGGING
AS SELECT * FROM ZZ_PLANNING_DATA;

1 个答案:

答案 0 :(得分:0)

试试这个:

ACCEPT QTR_END DATE PROMPT 'Enter the last day of the period you wish to run (i.e.: 30-JUN-2014).';

col quarter form a30 new_value quarter
col accyear form a30 new_value accyear

select TO_CHAR(TO_DATE('&&QTR_END','DD-MM-YYYY'), 'Q') quarter,
       TO_CHAR(EXTRACT (YEAR FROM TO_DATE('&&QTR_END','DD-MM-YYYY'))) accyear
from dual;

DEFINE BACKUP_TABLE_NAME = ZZ_PLANNING_DATA_&&QUARTER.Q&&ACCYEAR

prompt quarter: &quarter 
prompt accyear: &accyear
prompt backup_table_name: &backup_table_name

CREATE TABLE &&BACKUP_TABLE_NAME COMPRESS NOLOGGING
AS SELECT * FROM ZZ_PLANNING_DATA;

或者,我更容易在PLSQL中做到这一点:

ACCEPT QTR_END DATE PROMPT 'Enter the last day of the period you wish to run (i.e.: 30-JUN-2014).';

declare
  quarter VARCHAR2(6) := TO_CHAR(TO_DATE('&&QTR_END','DD-MM-YYYY'), 'Q');
  accyear VARCHAR2(6) := EXTRACT (YEAR FROM TO_DATE('&&QTR_END','DD-MM-YYYY'));
  backup_name varchar2(30) := 'ZZ_PLANNING_DATA_' || QUARTER || 'Q' || ACCYEAR;
begin
  execute immediate 'create table ' || backup_name || ' as select * from zz_planning_data';
end;
/