Postgresql: how to create table only if it does not already exist?

后端 未结 10 1099
不思量自难忘°
不思量自难忘° 2021-01-31 08:04

In Postgresql, how can I do a condition to create a table only if it does not already exist?

Code example appreciated.

10条回答
  •  旧时难觅i
    2021-01-31 08:18

    The best answer has been given by Skalli if you're running Postgresql 9.1+.

    If like me you need to do that with Postgresql 8.4, you can use a function with a 'duplicate_table' exception catch.

    This will ignore the generated error when the table exists and keep generating other errors.

    Here is an example working on Postgresql 8.4.10 :

    CREATE FUNCTION create_table() RETURNS VOID AS
    $$
    BEGIN
        CREATE TABLE my_table_name(my_column INT);
    EXCEPTION WHEN duplicate_table THEN
        -- Do nothing
    END;
    $$
    LANGUAGE plpgsql;
    

提交回复
热议问题