How to set a Postgresql default value datestamp like 'YYYYMM'?

前端 未结 6 1686
滥情空心
滥情空心 2021-02-05 00:09

As title, how can I set a table\'s column to have the default value the current year and month, in format \'YYYYMM\', like 200905 for today?

6条回答
  •  一生所求
    2021-02-05 00:42

    Right. Better to use a function:

    CREATE OR REPLACE FUNCTION yyyymm() RETURNS text
        LANGUAGE 'plpgsql' AS $$
    DECLARE
        retval text;
        m integer;
    BEGIN
        retval := EXTRACT(year from current_timestamp);
        m := EXTRACT(month from current_timestamp);
        IF m < 10 THEN retval := retval || '0'; END IF;
        RETURN retval || m;
    END $$;
    
    SELECT yyyymm();
    
    DROP TABLE foo;
    CREATE TABLE foo (
        key             int PRIMARY KEY,
        colname text DEFAULT yyyymm()
        );
    INSERT INTO foo (key) VALUES (0);
    SELECT * FROM FOO;
    

    This gives me

     key | colname 
    -----+---------
       0 | 200905
    

    Make sure you run createlang plpgsql from the Unix command line, if necessary.

提交回复
热议问题