Skip to content

Instantly share code, notes, and snippets.

@robertocommit
Created February 24, 2024 12:20
Show Gist options
  • Save robertocommit/154abb4caf0adf73255725d8c90271c1 to your computer and use it in GitHub Desktop.
Save robertocommit/154abb4caf0adf73255725d8c90271c1 to your computer and use it in GitHub Desktop.
Postgresql, copy public schema to staging schema
DO $$
DECLARE
table_rec record;
BEGIN
FOR table_rec IN SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public'
LOOP
IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'staging' AND table_name = table_rec.table_name) THEN
EXECUTE 'TRUNCATE TABLE staging.' || table_rec.table_name || ';';
ELSE
EXECUTE 'CREATE TABLE staging.' || table_rec.table_name || ' AS TABLE public.' || table_rec.table_name || ' WITH NO DATA;';
END IF;
EXECUTE 'INSERT INTO staging.' || table_rec.table_name || ' SELECT * FROM public.' || table_rec.table_name || ';';
END LOOP;
END $$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment