Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting timestamp in a COMMENT ON TABLE

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?

like image 740
Martin Avatar asked Mar 12 '23 04:03

Martin


1 Answers

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:

  • Error when setting n_distinct using a plpgsql variable
  • Table name as a PostgreSQL function parameter
  • To convert from Python arrays to PostgreSQL quickly?

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$;
like image 118
Erwin Brandstetter Avatar answered Apr 27 '23 06:04

Erwin Brandstetter