Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLITE Query results into a temp table

I haven't used SQLite before and can't figure out the syntax, I have this working in SQL Server if it helps.

I need to put the results into a temp table so I can reuse them.

//SQL Server

WITH FT_CTE AS
(
SELECT pID, cID FROM brFTNode_Children 
WHERE pID = 1
UNION ALL
    SELECT e.pID, e.cID FROM brFTNode_Children e
    INNER JOIN FT_CTE ftCTE on (ftCTE.cID = e.pID)
)
SELECT * INTO #ParentChild FROM FT_CTE;

//SQLite try

WITH FT_CTE AS
(
SELECT pID, cID FROM brFTNode_Children 
WHERE pID = 1
UNION ALL
    SELECT e.pID, e.cID FROM brFTNode_Children e
    INNER JOIN FT_CTE ftCTE on (ftCTE.cID = e.pID)
)
CREATE TEMPORARY TABLE ParentChild as SELECT * FROM FT_CTE;

I get Error near "CREATE": syntax error

like image 932
runfastman Avatar asked Oct 21 '14 16:10

runfastman


People also ask

How do I put query results in temp table?

INSERT INTO SELECT statement reads data from one table and inserts it into an existing table. Such as, if we want to copy the Location table data into a temp table using the INSERT INTO SELECT statement, we have to specify the temporary table explicitly and then insert the data.

How do you store a result of query in a temp table in SQL?

You can use select ... into ... to create and populate a temp table and then query the temp table to return the result. No you don't. If you want to fill a table that already exist with rows you need to use a different syntax.

Does SQLite have temp tables?

Technically, SQLite stores temporary tables in a separate temp database. It keeps that database in a separate file on disk, visible only to the current database connection. The temporary database is deleted automatically as soon as the connection is closed.


1 Answers

The CREATE TABLE statement does not allow CTEs, but the SELECT does:

CREATE TEMPORARY TABLE ParentChild AS
WITH FT_CTE AS (
    SELECT pID, cID FROM brFTNode_Children 
    WHERE pID = 1
    UNION ALL
    SELECT e.pID, e.cID FROM brFTNode_Children e
    INNER JOIN FT_CTE ftCTE ON (ftCTE.cID = e.pID)
)
SELECT * FROM FT_CTE;
like image 181
CL. Avatar answered Sep 19 '22 14:09

CL.