SQL 当不支持 IF EXISTS 运算符时,删除 SQLite 中的现有表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3675032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Drop existing table in SQLite, when IF EXISTS operator is not supported
提问by HyderA
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?
我的 SQLite 版本不支持IF EXISTS
运算符。如何删除可能存在或可能不存在的表而不会出现错误?
I can't update the version on a live application right now, so I cannot use a SQLite version that supports IF EXISTS
.
我现在无法在实时应用程序上更新版本,因此我无法使用支持IF EXISTS
.
采纳答案by Donal Fellows
The official documentationsays to use IF EXISTS, so I suspect your best plan is to upgrade.
在官方文件说,使用IF存在,所以我怀疑你的最佳方案就是升级。
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.
请注意,您需要在语言级别从这里捕获可能的错误,并且您可能希望将整个批次(探测、错误陷阱、删除表)包装在事务中。当然,如果您要进行错误处理,另一种方法是删除表并无论如何处理错误。
回答by Amit Jatrana
You can use:
您可以使用:
DROP TABLE IF EXISTS TABLE_NAME;
回答by Ahmad affandi
Just use this.
就用这个。
DROP TABLE TABLE_NAME;
回答by Marcus
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"