使用现有表

时间:2016-02-19 17:01:30

标签: postgresql plpgsql

我是plpgsql的新手。我确信有一些非常简单的方法可以做到这一点,但由于某种原因,我在尝试弄清楚如何做到这一点时遇到了很多麻烦。

我只是试图循环遍历现有表的列表并执行 CREATE TABLE z_existing_table_name AS SELECT * FROM existing_table_name WITH DATA 到目前为止,我有这个:

CREATE OR REPLACE FUNCTION create_backup_row()
RETURNS RECORD
AS $$
DECLARE
  row RECORD;

BEGIN
  FOR row IN SELECT * FROM information_schema.tables WHERE table_catalog = 'my_db' and table_schema = 'public'
  LOOP
     EXECUTE 'CREATE TABLE z_' || t.table_name || ' as ' || t.table_name
  END LOOP;
END;
$$ LANGUAGE plpgsql;

如果我能让这个功能重新运行,那将是一个额外的好处。像drop table这样的东西,如果存在然后创建表...

1 个答案:

答案 0 :(得分:1)

@Steven,请使用以下程序,

-- Function: create_backup_row()

-- DROP FUNCTION create_backup_row();

CREATE OR REPLACE FUNCTION create_backup_row()
  RETURNS integer AS
$BODY$

DECLARE
  v_table text;
BEGIN

FOR v_table IN
    SELECT table_name  
    FROM information_schema.tables 
    WHERE table_catalog = 'my_db' 
    AND table_schema = 'public'
    AND  table_name not ilike '%z_%'  -- to skip the table with z_ when we rerun it.
LOOP

   EXECUTE ' DROP TABLE IF EXISTS z_' || v_table ;
   EXECUTE 'CREATE TABLE z_' || v_table || ' as SELECT * FROM ' || v_table ;

END LOOP;

return 1;
    END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION create_backup_row()
  OWNER TO postgres;