Skip to content

Instantly share code, notes, and snippets.

@PostgreSqlStan
Last active April 27, 2023 13:12
Show Gist options
  • Save PostgreSqlStan/cb346c8971c2ccb9a4b8d9aba9bc497c to your computer and use it in GitHub Desktop.
Save PostgreSqlStan/cb346c8971c2ccb9a4b8d9aba9bc497c to your computer and use it in GitHub Desktop.
PostgreSQL PL/pgSQL procedure: creates staging table of numbered, text columns (f1, f2, f3…)
CREATE PROCEDURE create_text_table (fields INT, tablename TEXT = '_import')
AS $$
/*
DESCRIPTION create text-only staging table
ARGUMENTS fields: number of fields (columns)
tablename: [optional, default='_import'] name of table
*/
DECLARE
fieldlist TEXT := '';
BEGIN
SELECT string_agg(field, ', ' ORDER BY n)
FROM (SELECT 'f' || n || ' text' AS field, n
FROM generate_series(1, fields) AS gs(n) ) sq
INTO fieldlist;
EXECUTE FORMAT('CREATE UNLOGGED TABLE %I (%s)', tablename, fieldlist);
RAISE NOTICE '✅ created table % (% text fields)', tablename, fields;
END; $$
LANGUAGE plpgsql;
COMMENT ON PROCEDURE create_text_table(INT, TEXT) IS
'create unlogged table with specified # of text fields';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment