Create temp table in SQLite if another table exists

别来无恙 提交于 2019-12-04 05:56:52

问题


I need to create a temp table (which is a copy of Employees table) in a SQLite database, provided the table by the name of 'Employees' exists. There are only 2 columns in Employees table - EmployeeId (integer) and EmployeeName (varchar(100)).

Is there any way to implement the above using SQLite SQL?

Pseudo-code for intended SQL, which does not work in SQlite is as below. I hope there was something as powerful as the pseudo-code below in 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;

回答1:


SQLite has almost no control logic; as an embedded database, it is designed to be used together with a 'real' programming language.

You could just try to copy the data, and ignore the errors:

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

However, this would also suppress any other errors.

A better idea is to check explicitly whether the table exists:

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")


来源:https://stackoverflow.com/questions/22277612/create-temp-table-in-sqlite-if-another-table-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!