I want rename all column names to lower case in PostgreSQL database I have just coded a sql function. Below is the code.
CREATE OR REPLACE FUNCTION update_column_names() RETURNS boolean AS $$
DECLARE
aRow RECORD;
aRow2 RECORD;
tbl_name TEXT;
col_name TEXT;
new_col_name TEXT;
BEGIN
FOR aRow IN select table_name from information_schema.tables where table_schema='public' and table_type='BASE TABLE' LOOP
SELECT aRow.table_name INTO tbl_name from current_catalog;
FOR aRow2 IN select column_name from information_schema.columns where table_schema='public' and table_name = aRow.table_name LOOP
SELECT aRow2.column_name INTO col_name from current_catalog;
new_col_name:=lower(col_name);
RAISE NOTICE 'Table name:%',tbl_name;
RAISE NOTICE 'Column name:%',aRow2.column_name;
RAISE NOTICE 'New column name:%',new_col_name;
ALTER TABLE tbl_name RENAME COLUMN col_name TO new_col_name;
END LOOP;
END LOOP;
RETURN true;
END;
$$ LANGUAGE plpgsql;
The code above gives relation tbl_name does not exists. What is wrong with the code?
First, specify the table, which contains the column you want to rename, after the ALTER TABLE clause. Second, provide the column name after the RENAME COLUMN clause. Third, give the new column name after the TO keyword.
To change a column name, enter the following statement in your MySQL shell: ALTER TABLE table_name RENAME COLUMN old_column_name TO new_column_name; Replace table_name , old_column_name , and new_column_name with your table and column names.
You need to use dynamic SQL to do that; the table name can't be a variable.
⋮
EXECUTE 'ALTER TABLE ' || quote_ident(tbl_name) || ' RENAME COLUMN '
|| quote_ident(col_name) || ' TO ' || quote_ident(new_col_name);
⋮
or similar
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With