How to create sequence if not exists

后端 未结 6 1194
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 08:17

I tried to use code from Check if sequence exists in Postgres (plpgsql).

To create sequence if it does not exists. Running this code two times causes an exception:

6条回答
  •  孤街浪徒
    2020-12-09 08:53

    I went a different route: just catch the exception:

    DO
    $$
    BEGIN
            CREATE SEQUENCE myseq;
    EXCEPTION WHEN duplicate_table THEN
            -- do nothing, it's already there
    END
    $$ LANGUAGE plpgsql;
    

    One nice benefit to this is that you don't need to worry about what your current schema is.

提交回复
热议问题