问题描述
我需要在SQLite数据库中创建一个临时表(这是Employees表的副本),前提是存在名为"Employees"的表.员工表中只有两列-EmployeeId(整数)和EmployeeName(varchar(100)).
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)).
有什么方法可以使用SQLite SQL来实现上述目的?
预期的SQL伪代码如下所示,该伪代码在SQlite中不起作用.我希望它能像下面的SQLite中的伪代码一样强大.
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;
推荐答案
SQLite几乎没有控制逻辑.作为嵌入式数据库,它被设计为与真实"编程语言一起使用.
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")
这篇关于如果存在另一个表,则在SQLite中创建临时表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!