Just use text
or varchar
, not varchar(n)
. If you really need to restrict a column to a maximum length use a CHECK
constraint. Related answer:
Anyway, the basic statement is:
ALTER TABLE tbl ALTER clm TYPE varchar(50); -- or rather: text
You don't need a USING
clause with explicit conversion instructions, as long as there an implicit a cast registered, which is the case for varchar(n)
-> varchar(n)
/ text
. Details:
Script based on system catalogs:
DO
$do$
DECLARE
_sql text;
BEGIN
FOR _sql IN
SELECT format('ALTER TABLE %s ALTER %I TYPE varchar(50)'
, attrelid::regclass
, a.attname)
FROM pg_namespace n
JOIN pg_class c ON c.relnamespace = n.oid
JOIN pg_attribute a ON a.attrelid = c.oid
WHERE n.nspname = 'public' -- your schema
AND a.attname = 'clm' -- column name (case sensitive!)
AND a.attnum > 0
AND NOT a.attisdropped
LOOP
RAISE NOTICE '%', _sql; -- debug before you execute
-- EXECUTE _sql;
END LOOP;
END
$do$;