views:

131

answers:

2

My version of sqlite does not support IF EXISTS operator. So how can I drop a table which may or may not exist without getting an error slapped at me?

EDIT: FYI, IF EXISTS and IF NOT EXISTS were added to SQLite 3.3.0 http://www.sqlite.org/releaselog/3_3_0.html.

That's not my solution though, I can't update the version on a live application right now.

+2  A: 

The official documentation says to use IF EXISTS, so I suspect your best plan is to upgrade.

If you can't, you need to see whether you can do some trivial operation on the table that will succeed whether or not the table is empty; if it succeeds you should delete the table, if it fails the table is already gone. An example of the sort of operation to try might be:

SELECT COUNT(*) FROM theTable;

Note that you need to trap the possible error from this at the language level, and you might want to wrap the whole lot (probe, error-trap, drop table) in a transaction. Of course, the other approach if you're getting into error handling is to just drop the table and handle the error anyway.

Donal Fellows
A: 

You could somehow use the metadata table in your query to find out if the table exist:

SELECT count(*) > 0 FROM sqlite_master where tbl_name = "<table_name>" and type="table"
Marcus
Hmm... how would I use that when dropping the table?
gAMBOOKa
can't you write "if (SELECT count(*) FROM sqlite_master where tbl_name = "<table_name>" and type="table") > 0 then drop table <table_name>" Don't know if that's correct syntax for sqlite though.
Marcus