6

I'm regularly re-creating a table in PostgreSQL (9.4.1), much like this:

DROP TABLE IF EXISTS test.foo;
CREATE TABLE test.foo AS
  SELECT * FROM test.dagi_kommune
  WHERE ST_Area(wkb_geometry) < 500;

I would like to add a comment to the table, stating when the table was created. There are no problem creating a basic comment, like this:

COMMENT ON TABLE test.foo IS 'Table create date: ';

And I can also generate a independent time stamp, like this:

SELECT to_char(LOCALTIMESTAMP, 'YYYY-MM-DD HH:MI:SS');

But if I try to put the time stamp into the comment, like this:

COMMENT ON TABLE test.foo IS to_char(LOCALTIMESTAMP, 'YYYY-MM-DD HH:MI:SS');

I get the following response:

ERROR:  syntax error at or near "to_char"
LINE 10: COMMENT ON TABLE test.foo IS to_char(LOCALTIMESTAMP, 'YYYY-M...
                                  ^

********** Error **********

ERROR: syntax error at or near "to_char"
SQL state: 42601
Character: 276

How can I get a current 'date and time' stamped into the table's comment?

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
Martin
  • 391
  • 1
  • 4
  • 15

3 Answers3

9

You have to build and execute the statement as dynamic SQL.

DO
$do$
BEGIN
EXECUTE 'COMMENT ON TABLE b2 IS ''Table create date: '
     || to_char(LOCALTIMESTAMP, 'YYYY-MM-DD HH:MI:SS')
     || '''';
END
$do$

Plain concatenation is safe in this case, for unsafe input, use format() accordingly. See:

Line breaks are optional. The same as one-liner for scripting:

DO $do$BEGIN EXECUTE 'COMMENT ON TABLE b2 IS ''Table create date: ' || to_char(LOCALTIMESTAMP, 'YYYY-MM-DD HH:MI:SS') || ''''; END $do$;
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
  • Thanks. It's sort of clumsy, like in too many lines, for the use I had in mind. It would considerably clutter my SQL scripts. But now I know how to do it. – Martin May 30 '16 at 08:43
1

If you will be executing your commands using psql the following is a clean and concise method using psql variables:

SELECT current_timestamp AS now
\gset
COMMENT ON TABLE test.foo IS :'now';
Spencer Mathews
  • 135
  • 1
  • 7
0

Enhancing Spencer's comment above:

SELECT current_timestamp as dump_time
\gset
COMMENT ON SCHEMA my_schema IS 'Latest dump at: ':'dump_time';
kerfuffle
  • 168
  • 1
  • 10