How would I do the following TSQL query in DB2? I'm having problems creating a temp table based on the results from a query.
SELECT
COLUMN_1, COLUMN_2, COLUMN_3
INTO #TEMP_A
FROM TABLE_A
WHERE COLUMN_1 = 1 AND COLUMN_2 = 2
The error message is:
"Error: SQL0104N An unexpected token "#TEMP_A" was found following "". Expected tokens may include: ":". SQLSTATE=42601"
Temporary tables can help you identify a small subset of rows from an intermediate result table that you want to store permanently. The two types of temporary tables are created temporary tables and declared temporary tables. You can use temporary tables to sort large volumes of data and to query that data.
A valuable alternatives for the SQL temp table and table variable are SCHEMA_ONLY Memory-Optimized tables and the Memory-optimized Table Variable, where the data will be completely stored in the memory without the need to touch the TempDB database, providing the best data access performance.
Temp Tables are physically created in the tempdb database. These tables act as the normal table and also can have constraints, an index like normal tables. CTE is a named temporary result set which is used to manipulate the complex sub-queries data. This exists for the scope of a statement.
Looking at SQL Profiler results from these queries (each were run 10 times and averages are below) we can see that the CTE just slightly outperforms both the temporary table and table variable queries when it comes to overall duration.
You have to declare a temp table in DB2 before you can use it. Either with the same query you are running:
DECLARE GLOBAL TEMPORARY TABLE SESSION.YOUR_TEMP_TABLE_NAME AS (
SELECT COLUMN_1, COLUMN_2, COLUMN_3
FROM TABLE_A
) DEFINITION ONLY
Or "manually" define the columns:
DECLARE GLOBAL TEMPORARY TABLE SESSION.YOUR_TEMP_TABLE_NAME (
COLUMN_1 CHAR(10)
,COLUMN_2 TIMESTAMP
,COLUMN_3 INTEGER
)
Then populate it:
INSERT INTO SESSION.YOUR_TEMP_TABLE_NAME
SELECT COLUMN_1, COLUMN_2, COLUMN_3
FROM TABLE_A
WHERE COLUMN_1 = 1
AND COLUMN_2 = 2
It's not quite as straight-forward as in SQL Server. :)
And even though it's called a "global" temporary table, it only exists for the current session. Note that all temp tables should be prefixed with the SESSION
schema. If you do not provide a schema name, then SESSION
will be implied.
maybe the "with" clause is what you look for:
with TEMP_A as (
SELECT COLUMN_1, COLUMN_2, COLUMN_3
FROM TABLE_A
WHERE COLUMN_1 = 1 AND COLUMN_2 = 2
)
-- now use TEMP_A
select * from TEMP_A
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With