Search code examples
sqlitecordovahybrid-mobile-app

Create temp table in SQLite if another table exists


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;

Solution

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