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

前端 未结 6 1685
滥情空心
滥情空心 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:34

    Please bear in mind that the formatting of the date is independent of the storage. If it's essential to you that the date is stored in that format you will need to either define a custom data type or store it as a string. Then you can use a combination of extract, typecasting and concatenation to get that format.

    However, I suspect that you want to store a date and get the format on output. So, something like this will do the trick for you:

        CREATE TABLE my_table
        (
        id serial PRIMARY KEY not null,
        my_date date not null default CURRENT_DATE
        );
    
    (CURRENT_DATE is basically a synonym for now() and a cast to date).
    

    (Edited to use to_char).

    Then you can get your output like:

    SELECT id, to_char(my_date, 'yyyymm') FROM my_table;
    

    Now, if you did really need to store that field as a string and ensure the format you could always do:

    CREATE TABLE my_other_table
    (
    id serial PRIMARY KEY not null,
    my_date varchar(6) default to_char(CURRENT_DATE, 'yyyymm')
    );
    

提交回复
热议问题