1

I need to create tables on daily basis with name as date in form at (yyMMdd), I tried this :

dbadmin=> \set table_name 'select to_char(current_date, \'yyMMdd \')'
dbadmin=> :table_name;

to_char
---------
150515
(1 row)

and then tried to create table with table name from the set parameter :table_name, but got this

dbadmin=> create table :table_name(col1 varchar(1));
ERROR 4856: Syntax error at or near "select" at character 14
LINE 1: create table select to_char(current_date, 'yyMMdd ')(col1 va...

Is there a way where i could store a value in a variable and then use that variable as table name or to assign priority that the inner select statement has execute first to give me the name i require.

Please suggest!!!

PravinS
  • 2,640
  • 3
  • 21
  • 25
Kundan Jha
  • 74
  • 9

1 Answers1

1

Try this

  • for what ever reason the variable stored comes with some space and i had to remove it and also cannot start naming table starting with numbers so i had to add something in form like tbl_
  • in short you just need to store the value of the exit so you need to do some extra work and execute the query.

    \set table_name `vsql -U dbadmin -w d -t -c "select concat('tbl_',replace(to_char(current_date, 'yyMMdd'),' ',''))"`
    

Create table:

create table :table_name(col1 varchar(1));
(dbadmin@:5433) [dbadmin] *> \d tbl_150515
Schema      | public
Table       | tbl_150515
Column      | col1
Type        | varchar(1)
Size        | 1
Default     |
Not Null    | f
Primary Key | f
Foreign Key |
woot
  • 7,406
  • 2
  • 36
  • 55
Up_One
  • 5,213
  • 3
  • 33
  • 65