What is the best approach to parameterize a recursive query?
As an example, let's take the following query: (taken from postgresqltutorial):
WITH RECURSIVE subordinates AS (
SELECT
employee_id,
manager_id,
full_name
FROM
employees
WHERE
employee_id = 2
UNION
SELECT
e.employee_id,
e.manager_id,
e.full_name
FROM
employees e
INNER JOIN subordinates s ON s.employee_id = e.manager_id
)
SELECT *
FROM subordinates;
How could I modify it to allowed me to pass employee_id as a parameter or clause of my query?
I found a solution where I put this query in a function that receives employee_id as parameter and return a table (with employee_id, manager_id, full_name columns), but I'm not sure if this is a good/elegant solution.
CREATE OR REPLACE FUNCTION func_subordinates(employee_id_param INT)
RETURNS TABLE (
employee_id INT,
full_name VARCHAR,
manager_id INT) AS
$BODY$
BEGIN
RETURN QUERY
WITH RECURSIVE subordinates AS (
SELECT
employee_id,
manager_id,
full_name
FROM
employees
WHERE
employee_id = employee_id_param
UNION
SELECT
e.employee_id,
e.manager_id,
e.full_name
FROM
employees e
INNER JOIN subordinates s ON s.employee_id = e.manager_id
)
SELECT *
FROM subordinates;
IF NOT FOUND THEN
RAISE EXCEPTION 'No found %.', 1ドル;
END IF;
RETURN;
END;
$BODY$
LANGUAGE plpgsql;
Could I get the same result using a VIEW where employee_id could be passed as a clause or something like that?
Any suggestion will really appreciated.
LANGUAGE sql;