0

postgesql 9.6.17

There are result rows from Renaming multiple columns in PostgreSQL

they contain some commands like

alter table .....
alter table .....

how to immediately exec them in sql like

SELECT
    EXEC SQL 'ALTER TABLE ' || tab_name || ' RENAME COLUMN '
    || quote_ident(column_name) || ' TO '
    || lower(quote_ident( column_name)) || ';' commit
FROM (
    SELECT
        quote_ident(table_schema) || '.' || quote_ident(table_name) as tab_name,
        column_name
    FROM information_schema.columns  
    WHERE 
            table_schema = 'public'
) sub;

but example ↑ fails

2
  • I think you mean EXECUTE Also: your code is incomplete and cannot be tested. Commented Apr 27, 2020 at 12:07
  • example is fully complete. i want to do lower() for all column names of all my tables, so i got an alter table - query in rows, but it is huge, and i ask, how to execute them in sql Commented Apr 27, 2020 at 12:33

1 Answer 1

1

You can use the DO statement for executing this. Something like given below:

DO $$
DECLARE rec TEXT;
BEGIN
  FOR rec in SELECT
            'ALTER TABLE ' || tab_name || ' RENAME COLUMN '
            || quote_ident(column_name) || ' TO '
            || lower(quote_ident( column_name))
          FROM (
              SELECT
                  quote_ident(table_schema) || '.' || 
                  quote_ident(table_name) as tab_name,
                  column_name
                  FROM information_schema.columns  
              WHERE 
                   table_schema = 'public'
            ) sub
  LOOP
    EXECUTE rec;
  END LOOP;
END $$;

For more detail refer the following link: https://www.postgresql.org/docs/9.6/sql-do.html

Sign up to request clarification or add additional context in comments.

2 Comments

just please fix, instead FOR r in SELECT there should be FOR rec in SELECT
please update to use rec

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.