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

后端 未结 10 932
不思量自难忘°
不思量自难忘° 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条回答
  •  野的像风
    2021-01-31 08:14

    create or replace function update_the_db() returns void as
    $$
    begin
    
        if not exists(select * from information_schema.tables 
            where 
                table_catalog = CURRENT_CATALOG and table_schema = CURRENT_SCHEMA
                and table_name = 'your_table_name_here') then
    
            create table your_table_name_here
            (
                the_id int not null,
                name text
            );
    
        end if;
    
    end;
    $$
    language 'plpgsql';
    
    select update_the_db();
    drop function update_the_db();
    

提交回复
热议问题