How to create a table only if it does not exist?


Or, how to create any object only if it does not exist.
Or, how to drop any object only if it exists.

This becomes easy using the new EXECUTE STATEMENT feature and some knowlegde of system tables. While you can't write DDL statements in PSQL (stored procedure and trigger bodies), and you can't use IF outside of PSQL, you can use EXECUTE STATEMENT in PSQL. Example:

if (not exists(select 1 from rdb$relations where rdb$relation_name = 'EMPLOYEE')) then
execute statement 'create table employee ( id integer );';


This is fine, but now it seems you need to create a special stored procedure for this. Well, we use another new feature: EXECUTE BLOCK to make it a single statement:

SET TERM !! ;
EXECUTE BLOCK AS BEGIN
if (not exists(select 1 from rdb$relations where rdb$relation_name = 'EMPLOYEE')) then
execute statement 'create table employee ( id integer );';
END!!
SET TERM ; !!


Those SET TERM statements are only needed if you work from an administration tool like isql or FlameRobin. If you run it from your application code, just send the EXECUTE BLOCK block as a single statement.

Similar procedure can be used to drop objects and do various other metadata manipulations from plain SQL.


Do you find this FAQ incorrect or incomplete? Please e-mail us what needs to be changed. To ensure quality, each change is checked by our editors (and often tested on live Firebird databases), before it enters the main FAQ database. If you desire so, the changes will be credited to your name. To learn more, visit our add content page.



All contents are copyright © 2007-2024 FirebirdFAQ.org unless otherwise stated in the text.


Links   Firebird   News   FlameRobin   Powered by FB: Home Inventory   Euchre  
Add content   About  

Categories
 Newbies
 SQL
 Installation and setup
 Backup and restore
 Performance
 Security
 Connectivity and API
 HOWTOs
 Errors and error codes
 Miscellaneous