I want to use a variable in TOAD for an WITH-SQL-Statement because today's date is used multiple times.
I tried with variable, DEFINE and Declare for setting the variable up but it didn't work yet.
Skript should look something like this:
DECLARE TODAY date := SYSDATE();
BEGIN
WITH
SUBQUERY1 AS (
SELECT *
FROM TABLE
WHERE TABLE.DATE = &TODAY
),
SUBQUERY2 AS (
SELECT *
FROM TABLE2
WHERE TABLE2.DATE = &TODAY
),
SELECT *
FROM TABLE3
JOIN SUBQUERY1 ON TABLE3.PRIMARYKEY = SUBQUERY1.PRIMARYKEY
JOIN SUBQUERY2 ON TABLE3.PRIMARYKEY = SUBQUERY2.PRIMARYKEY
END;
While researching I've read something about an into statement but I think it's used when you want to define the output of the query to the variable? Maybe someone can also provide me with an helpful article or so on.
Don't use PL/SQL, just use a query (and make sure you have closing brackets for the sub-query factoring clauses and a comma between them):
WITH dates (dt) AS (
SELECT SYSDATE
FROM DUAL
),
SUBQUERY1 AS (
SELECT t.*
FROM TABLE t
INNER JOIN dates d
ON (t.DATE = d.dt)
),
SUBQUERY2 AS (
SELECT t2.*
FROM TABLE2 t2
INNER JOIN dates d
ON (t2.DATE = d.dt)
)
SELECT *
FROM TABLE3
JOIN SUBQUERY1 ON TABLE3.PRIMARYKEY = SUBQUERY1.PRIMARYKEY
JOIN SUBQUERY2 ON TABLE3.PRIMARYKEY = SUBQUERY2.PRIMARYKEY
Note: You do not need a variable for the date.
In Oracle, a DATE
always has date and time components (even if the client application does not always show it). If you want results for the entire day (rather than for the current instant) then use:
WITH dates (dt) AS (
SELECT TRUNC(SYSDATE)
FROM DUAL
),
SUBQUERY1 AS (
SELECT t.*
FROM TABLE t
INNER JOIN dates d
ON ( t.DATE >= dt
AND t.DATE < dt + INTERVAL '1' DAY)
),
SUBQUERY2 AS (
SELECT t2.*
FROM TABLE2 t2
INNER JOIN dates d
ON ( t2.DATE >= dt
AND t2.DATE < dt + INTERVAL '1' DAY)
)
SELECT *
FROM TABLE3
JOIN SUBQUERY1 ON TABLE3.PRIMARYKEY = SUBQUERY1.PRIMARYKEY
JOIN SUBQUERY2 ON TABLE3.PRIMARYKEY = SUBQUERY2.PRIMARYKEY