· 8 years ago · Mar 16, 2018, 12:22 AM
1CREATE OR REPLACE FUNCTION copy_table(_source_tbl regclass, _target_tbl text)
2 RETURNS bool AS $func$
3DECLARE query_str text;
4BEGIN
5 query_str = format($fmt$ DROP TABLE IF EXISTS %1$I; CREATE TABLE %1$I AS (TABLE %s); $fmt$, _target_tbl, _source_tbl);
6 EXECUTE query_str;
7 RAISE NOTICE '%', query_str;
8 RETURN True;
9END $func$ LANGUAGE plpgsql;
10
11=> SELECT copy_table('ex.test', 'ex.test1');
12NOTICE: table "ex.test1" does not exist, skipping
13NOTICE: DROP TABLE IF EXISTS "ex.test1"; CREATE TABLE "ex.test1" AS (TABLE ex.test);
14
15=> dt ex.test1
16Did not find any relation named "ex.test1".
17=> dt "ex.test1"
18 List of relations
19 Schema | Name | Type | Owner
20--------+----------+-------+-------
21 public | ex.test1 | table |
22(1 row)