简体   繁体   中英

Using Global Temporary Table with CTE in Firebird SQL

I am trying to use a Global Temporary Table with CTE in Firebird SQL, but I'm not sure how.

Below is sample code of what I am trying to accomplish

CREATE GLOBAL TEMPORARY TABLE temp_table ( Y INTEGER, K INTEGER );        

WITH J AS (SELECT Y , K FROM X), 
 
INSERT INTO temp_table 

T AS (SELECT Y , K FROM Z INNER JOIN J ON Z.Y=J.Y),


P AS (SELECT R , K FROM U INNER JOIN T ON U.K=T.K)


SELECT R , K , Y FROM P LEFT JOIN temp_table ON P.K=temp_table.K

My objective is to store values from a CTE in a temporary table and access those values a with a left join. In my specific situation doing a left join directly in a previous CTE will make the run very, very slow because one of the tables involved is a big one. I thought maybe making a temporary table will go around this.

In Firebird SQL, you cannot directly use a Global Temporary Table (GTT) within a CTE (Common Table Expression) in the same statement. However, you can achieve your objective by using a combination of temporary tables and multiple SQL statements.

Here's an example of how you can modify your code to achieve the desired result:

-- Create a temporary table to store the CTE results
CREATE GLOBAL TEMPORARY TABLE temp_table (Y INTEGER, K INTEGER);

-- Insert the CTE results into the temporary table
INSERT INTO temp_table (Y, K)
SELECT Y, K
FROM (
-- Define the CTE
WITH J AS (SELECT Y, K FROM X),
T AS (SELECT Y, K FROM Z INNER JOIN J ON Z.Y = J.Y),
P AS (SELECT R, K FROM U INNER JOIN T ON U.K = T.K)
SELECT R, K, Y
FROM P
) CTE_results;

-- Use the temporary table in a separate SELECT statement with a LEFT JOIN
SELECT R, K, Y
FROM P
LEFT JOIN temp_table ON P.K = temp_table.K;

In this code, we first create the temporary table temp_table to store the results of the CTE. Then, we insert the CTE results into the temporary table using a separate INSERT INTO statement. Finally, we can use the temporary table in a separate SELECT statement with a LEFT JOIN to access the stored values.

Keep in mind that the temporary table will only be accessible within the same database connection session. It will be automatically dropped when the session ends or when the transaction is committed or rolled back.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM