I'm learning PostgreSQL and I'm trying to create a function to ALTER the data types of a given table that has columns with character varying
data type.
To achieve this, I've built a cursor that basically queries the information_schema.columns looking for tables that has columns with type character varying
to later execute an alter and try to alter the column to text
, so that field is not limited by the length of the value.
Here is the function:
CREATE OR REPLACE FUNCTION my_cursor(db_name TEXT, tbl_schema TEXT, tbl_name TEXT, col_type TEXT) RETURNS void AS $func$
DECLARE
cid record;
BEGIN
FOR cid IN SELECT * FROM information_schema.columns AS ic
WHERE ic.table_catalog=db_name
AND ic.table_schema=tbl_schema
AND ic.table_name=tbl_name
AND ic.data_type=col_type
LOOP
EXECUTE format('ALTER TABLE %I.%I ALTER COLUMN %I TYPE text', cid.table_schema, cid.table_name, cid.column_name);
END LOOP;
RETURN;
END;
$func$ LANGUAGE plpgsql;
SELECT my_cursor('database10232016', 'public', 'continent', 'character varying');
The function compiles and is created successfully, however after running the function I noticed the alter is not running over the table name specified.
Can you help me to identify what went wrong with my cursor?