I have a simple function which is used to count rows in a data frame (recycling code from this tutorial here) in an Oracle database.
CREATE OR REPLACE FUNCTION TABCOUNT (tbl_name IN VARCHAR2)
RETURN PLS_INTEGER
IS
retval PLS_INTEGER;
BEGIN
EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ' || tbl_name INTO retval;
RETURN retval;
END;
If I want to apply this function to a stored table, it executes fine:
CREATE TABLE EXAMPLE_TABLE ("ROW_ID" INT);
INSERT INTO EXAMPLE_TABLE VALUES (1);
INSERT INTO EXAMPLE_TABLE VALUES (2);
SELECT TABCOUNT('EXAMPLE_TABLE') AS "N_ROW" FROM DUAL;
However, I would like to use this type of a function inside a CTE, as shown below.
WITH TABLE_1 AS (SELECT * FROM EXAMPLE_TABLE)
SELECT 'T1' AS "TABLE_NAME", TABCOUNT (TABLE_1) AS "N_ROW"
FROM DUAL;
For some reason, I can't get this to run. Can anybody show me how to do so? Apologies if this is an elementary question as I am quite new to PL/SQL functions.
The simplified reason I would like to do this in a CTE is because, using the example above, I would like to apply it to a variety of different tables in the CTE and union the results, i.e.:
Edit: In the example below, 'EXAMPLE_TABLE' and 'EXAMPLE_TABLE_2' are placeholders. Imagine that TABLE_1 and TABLE_2 are intermediate tables that result from processing further up the query. 'EXAMPLE_TABLE' and 'EXAMPLE_TABLE_2' were included simply to make the CTE in the example run.
CREATE TABLE EXAMPLE_TABLE_2 AS SELECT * FROM EXAMPLE_TABLE;
WITH TABLE_1 AS (SELECT * FROM EXAMPLE_TABLE),
TABLE_2 AS (SELECT * FROM EXAMPLE_TABLE_2)
SELECT 'T1' AS "TABLE_NAME", TABCOUNT (TABLE_1) AS "N_ROW" FROM DUAL
UNION ALL
SELECT 'T2' AS "TABLE_NAME", TABCOUNT (TABLE_2) AS "N_ROW" FROM DUAL;