【问题标题】:Create temp table in SQLite if another table exists如果存在另一个表,则在 SQLite 中创建临时表
【发布时间】:2017-06-11 01:12:13
【问题描述】:

如果存在名为“Employees”的表,我需要在 SQLite 数据库中创建一个临时表(它是Employees 表的副本)。 Employees 表中只有 2 列 - EmployeeId (integer) 和 EmployeeName (varchar(100))。

有什么方法可以使用 SQLite SQL 来实现上述功能吗?

在 SQlite 中不起作用的预期 SQL 的伪代码如下。我希望 SQLite 中能有像下面的伪代码一样强大的东西。

--if Employees table exists then create a temp table and populate it with all 
--rows from Employees table
CREATE TEMP TABLE tempEmployees if exists Employees as select *  from Employees;

【问题讨论】:

    标签: sqlite cordova hybrid-mobile-app


    【解决方案1】:

    SQLite 几乎没有控制逻辑;作为嵌入式数据库,它旨在与“真正的”编程语言一起使用。

    您可以尝试复制数据并忽略错误:

    try:
        c.execute("CREATE TEMP TABLE tempEmployees AS SELECT * FROM Employees")
    except:
        pass
    

    但是,这也会抑制任何其他错误。

    更好的办法是明确检查表是否存在:

    c.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='Employees'")
    if c.fetchone():
        c.execute("CREATE TEMP TABLE tempEmployees AS SELECT * FROM Employees")
    

    【讨论】:

    • 您是否在粘贴的代码中使用 Python?所以看起来,需要依赖于所使用的过程语言,在我的例子中是 JavaScript,因为我正在开发一个 Cordova 混合应用程序。
    • sqlite 允许在创建语句中检查表是否存在...CREATE TEMP TABLE IF NOT EXISTS tempEmployees
    • @user3188040 必须检查的是source表。
    猜你喜欢
    • 2017-07-19
    • 2013-09-21
    • 2014-03-17
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多