Append sysdate to a table name in Oracle

Sid picture Sid · Apr 16, 2013 · Viewed 12.7k times · Source

I need to append SYSDATE while creating a table in Oracle. Please let me know if there is a direct way of doing it (Using only SQL) or I have to use PL/SQL for the same.

E.g. If table name is ABC, I need to create table as ABC_20130416.

Let me know if more info is needed.

Answer

Colin 't Hart picture Colin 't Hart · Apr 16, 2013

If SQL*Plus will always be available, you can do this using variables, something like (untested):

SQL>col yyyymmdd for a8 new_value v
SQL>select to_char(sysdate, 'YYYYMMDD') as yyyymmdd from dual;
SQL>create table ABC_&v (col1 integer);

On the other hand, if you want to able to do it anywhere you will need PL/SQL and dynamic SQL:

declare
  l_tablename varchar2(30) := 'ABC_' || to_char(sysdate, 'YYYYMMDD')
begin
  execute immediate 'create table ' || l_tablename || ' (col1 integer)';
end;
/

Or just create the table normally first and then rename:

create table xyz (
  ... many columns ...
);

declare
  l_tablename varchar2(30) := 'ABC_' || to_char(sysdate, 'YYYYMMDD')
begin
  execute immediate 'rename xyz to ' || l_tablename;
end;
/