My version of SQLite does not support the IF EXISTS
operator. How can I drop a table which may or may not exist without getting an error slapped at me?
I can't update the version on a live application right now, so I cannot use a SQLite version that supports IF EXISTS
.
The DROP TABLE statement deletes the specified table, and any data associated with it, from the database. The IF EXISTS clause allows the statement to succeed even if the specified tables does not exist. If the table does not exist and you do not include the IF EXISTS clause, the statement will return an error.
Normally in SQL you drop foreign keys with the ALTER TABLE statement, but SQLite's ALTER TABLE implementation doesn't allow for dropping constraints. There is a way to deal with this situation though.
To drop a table in SQLite, use the DROP TABLE statement. Running this statement removes the table from the database. It is completely removed from the database schema and the disk file. Therefore the table can not be recovered.
WHERE clause mainly used along with the DELETE command. No clause required along with DROP command. Actions performed by DELETE can be rolled back as it uses buffer. Actions performed by DROP can't be rolled back because it directly works on actual data.
You can use:
DROP TABLE IF EXISTS TABLE_NAME;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With