Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Drop column only if it exists

Status
Not open for further replies.

sakkara

Programmer
Jun 18, 2007
4
AU
Hi,
How do I drop a column within a table, ONLY if it exists?

I have hunted around but no luck in finding any solution.

Thank you.
 
U mean how to do it with pl function?
All information about database u can find in information_schema tables and views. With an IF statement and NOT FOUND 'constant' u can check if specified table contains given column. (see more on postgresql.org)
 
if you are using recent version of postgresql
and using plain SQL, just enclose it with savepoint

test@ws-dev:5432 test=> ALTER TABLE tbl DROP field;
ALTER TABLE
test@ws-dev:5432 test=*> SAVEPOINT test_1;
SAVEPOINT
test@ws-dev:5432 test=*> ALTER TABLE tbl DROP field;
ERROR: column "field" of relation "tbl" does not exist
test@ws-dev:5432 test=!> ROLLBACK TO SAVEPOINT test_1;
ROLLBACK
test@ws-dev:5432 test=*>

if it goes OK instead of ROLLBACK TO SAVEPOINT you do RELEASE SAVEPOINT

(in function, beside this method, you can use exceptions)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top