使用sysdate更改表名

时间:2015-01-05 10:08:11

标签: sql oracle

我想通过向其添加SYSDATE来更改表名。例如,我想将表格EXAMPLE_TABLE更改为EXAMPLE_TABLE_05_01_2015,但我希望从SYSDATE获取日期。

我准备了以下内容,但它无法正常工作:

ALTER TABLE "MYDB"."EXAMPLE_TABLE" rename to (SELECT 'EXAMPLE_TABLE' || TO_CHAR(SYSDATE, '_dd_MM_yyyy') FROM DUAL);

我怎样才能让它发挥作用?

这是错误:

SQL Error: ORA-14047: ALTER TABLE|INDEX RENAME may not be combined with other operations
14047. 00000 -  "ALTER TABLE|INDEX RENAME may not be combined with other operations"
*Cause:    ALTER TABLE or ALTER INDEX statement attempted to combine
           a RENAME operation with some other operation which is illegal
*Action:   Ensure that RENAME operation is the sole operation specified in
           ALTER TABLE or ALTER INDEX statement;

2 个答案:

答案 0 :(得分:6)

使用execute immediate

begin
   execute immediate 
   'alter table mydb.example_table rename to ' ||
   'example_table_' || to_char(sysdate, 'dd_mm_yyyy');
end;
/

那就是说,我预感到你最好不要使用分区表。

答案 1 :(得分:0)

SQL*Plus 中,您可以使用variable substitution

另一种方式

SQL> CREATE TABLE t(ID NUMBER)
  2  /

Table created.

SQL>
SQL> COLUMN new_tablename NEW_VALUE new_tablename
SQL> SELECT 't_' || to_char(sysdate, 'dd_mm_yyyy') AS new_tablename from dual
  2  /

NEW_TABLENAM
------------
t_05_01_2015

SQL>
SQL> RENAME t TO &new_tablename
  2  /
old   1: RENAME t TO &new_tablename
new   1: RENAME t TO t_05_01_2015

Table renamed.

SQL>
SQL> select * from t_05_01_2015;

no rows selected

SQL>

因此,现在表格T重命名为T_05_01_2015