Friday, August 15, 2008

Dev : MsSQL Drop Only If Exist

If you were to execute "DROP TABLE table1" or "ALTER TABLE table1 DROP COLUMN field1" in MsSQL server, probably you'll encouter error complaining the table or the column does not exist.

So how do you verify such table or column existed before you could drop them? There is a way. By querying the "INFORMATION_SCHEMA" table, you should be able to drop it without the concern of getting error.

Instead of "DROP TABLE table1", we can use
"if exists (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE table_name = 'table1')
DROP TABLE table1".

And instead of "ALTER TABLE table1 DROP COLUMN field1", we can use
"if exists (SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'table1'
and column_name = 'field1')
alter table table1
drop column field1".

No comments: