PostgreSQL: Create table if not exists AS

后端 未结 6 1318
不思量自难忘°
不思量自难忘° 2020-12-29 04:54

I\'m using PostgreSQL and am an SQL beginner. I\'m trying to create a table from a query, and if I run:

CREATE TABLE table_name AS
   (....query...)
<         


        
6条回答
  •  猫巷女王i
    2020-12-29 05:15

    If you are going to write a function for this, base it on system catalog table pg_class, not on views in the information schema or the statistics collector (which only exist if activated).

    • How to check if a table exists in a given schema

    CREATE OR REPLACE FUNCTION create_table_qry(_tbl text
                                              , _qry text
                                              , _schema text = NULL)
      RETURNS bool AS
    $func$
    DECLARE
      _sch text := COALESCE(_schema, current_schema());
    BEGIN
    
    IF EXISTS (
       SELECT 1 
       FROM   pg_catalog.pg_class c
       JOIN   pg_catalog.pg_namespace n ON n.oid = c.relnamespace
       WHERE  n.nspname = _sch
       AND    c.relname = _tbl
       ) THEN
    
       RAISE NOTICE 'Name is not free: %.%',_sch, _tbl;
       RETURN  FALSE;
    ELSE
    EXECUTE format('CREATE TABLE %I.%I AS %s', _sch, _tbl, _qry);
    
       RAISE NOTICE 'Table created successfully: %.%',_sch, _tbl;
       RETURN  TRUE;
    END IF;
    
    END
    $func$  LANGUAGE plpgsql;
    

    The function takes a table name and the query string, and optionally also a schema to create the table in (defaults to the current schema).

    Note the correct use of = in the function header and := in the function body:

    • The forgotten assignment operator "=" and the commonplace ":="

    Also note how identifiers are escaped as identifiers. You can't use regclass, since the table does not exist, yet:

    • Table name as a PostgreSQL function parameter

提交回复
热议问题