Tuesday, 10 August 2010

ALTER TABLE ADD COLUMN IF NOT EXISTS OR ADD COLUMN WITH incremental suffix IF EXISTS

A generic way to add a new column in PostgreSQL 8.3 from plpgsql by incrementing column suffix in a case when column already exists.

DECLARE
query TEXT :='';
suffix INTEGER :=0;
recs INTEGER :=0;
BEGIN

LOOP
suffix = suffix + 1;
EXECUTE 'SELECT count(*) FROM information_schema.columns
WHERE table_schema||$$.$$||table_name = $$'||mytablename||'$$
AND column_name = $$mycolumn'||suffix||'$$' INTO recs;
RAISE INFO 'recs %!', recs;
IF recs = 0 THEN
EXECUTE 'ALTER TABLE '||tablename||' ADD COLUMN class'||suffix||' INTEGER';
RAISE INFO 'Column mycolumn% was added!', suffix;
EXIT;
END IF;
END LOOP;

No comments: