postgresqltimestampdynamic-sqlddlpostgresql-9.4

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?


Solution

  • 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$;