I need some help with dynamic SQL and cursor. I have stored procedure which has DEFINE variables. How I can populate DEFINE variable using cursor?
I want to use another table as source for cursor and insert these results to another table.
Here is simplified example about my problem:
CREATE OR REPLACE PROCEDURE usp_TEST
AS
BEGIN
DEFINE vTable = 'TABLE_NAME'; -- How I can create cursor loop, so I can loop and change this table name using another table as source?
INSERT INTO results
WITH CTE_main
AS
(
SELECT
TABLE_NAME
FROM dest_TABLES
)
SELECT
'SELECT * FROM ' || '&vTable' || ' source INNER JOIN ' || cte.TABLE_NAME || ' dest ON source.ID = dest.ID;' AS query
FROM CTE_main cte
END;
Source table contains only table names:
TABLE_ONE
TABLE_TWO
etc...
Result should be something like this:
SELECT * FROM TABLE_ONE source INNER JOIN DEST_ONE dest ON source.ID = dest.ID;
SELECT * FROM TABLE_ONE source INNER JOIN DEST_TWO dest ON source.ID = dest.ID;
SELECT * FROM TABLE_TWO source INNER JOIN DEST_ONE dest ON source.ID = dest.ID;
SELECT * FROM TABLE_TWO source INNER JOIN DEST_TWO dest ON source.ID = dest.ID;
Are you after something like:
WITH dest_tables AS (SELECT 'TABLE_ONE' table_name FROM dual UNION ALL
SELECT 'TABLE_TWO' table_name FROM dual),
cte_main AS (SELECT 'DEST_ONE' table_name FROM dual UNION ALL
SELECT 'DEST_TWO' table_name FROM dual)
SELECT 'SELECT * FROM ' || dt.table_name || ' src INNER JOIN ' || cm.TABLE_NAME || ' dest ON src.ID = dest.ID;' AS query
FROM dest_tables dt
CROSS JOIN cte_main cm
ORDER BY dt.table_name, cm.table_name;
QUERY
-------------------------------------------------------------------------
SELECT * FROM TABLE_ONE src INNER JOIN DEST_ONE dest ON src.ID = dest.ID;
SELECT * FROM TABLE_ONE src INNER JOIN DEST_TWO dest ON src.ID = dest.ID;
SELECT * FROM TABLE_TWO src INNER JOIN DEST_ONE dest ON src.ID = dest.ID;
SELECT * FROM TABLE_TWO src INNER JOIN DEST_TWO dest ON src.ID = dest.ID;
? (NB I used the two subqueries in the with-clause to mimic data in your tables; you wouldn't need those two subqueries, you'd just use your tables instead.)
No PL/SQL is required, just SQL. You could take the above statement and use it in an insert statement inside a PL/SQL program, though.
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.