PostgreSQL: Create table if not exists AS

后端 未结 6 1319
不思量自难忘°
不思量自难忘° 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条回答
  •  鱼传尺愫
    2020-12-29 05:05

    CTAS (Create Table AS) for REDSHIFT PLPGSQL flavor. Shout out to Erwin Brandstetter for the root idea using pure PG syntax.

    CREATE
    OR
    REPLACE
    PROCEDURE pipeline.sp_create_table_if_not_exists_as (sch VARCHAR, tbl VARCHAR, qry VARCHAR, tbl_attrs VARCHAR)
     AS
        /*
         specifically an exception for CTAS functionality: https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_TABLE_AS.html
        */
    $$
    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 INFO 'Table already exists: %.%', sch, tbl;
    ELSE
        EXECUTE 'CREATE TABLE ' || sch || '.' || tbl || ' ' || tbl_attrs || ' AS ' || qry;
        RAISE INFO 'Table created successfully: %.%, using query: [%], optional attributes: [%]', sch, tbl, qry, tbl_attrs;
    END IF;
    
    END;
    $$
    language plpgsql;
    

提交回复
热议问题