Subject Re: [firebird-support] Recursive selectable stored procedures
Author Lele Gaifax
>>>>> Fulvio Senore writes:

Fulvio> Here is the question: is it possible to have a recursive
Fulvio> selectable stored procedure? In case it is possible, is
Fulvio> there an example somewhere?

Hi Fulvio, yes, I use them a lot, like in:

CREATE TABLE sequences (seq_id INTEGER PRIMARY KEY,
seq_prog SMALLINT,
id_type SMALLINT,
item_id INTEGER);

INSERT INTO sequences VALUES (1, 1, 1, 1);
INSERT INTO sequences VALUES (1, 2, 1, 2);
INSERT INTO sequences VALUES (1, 3, 0, 2);
INSERT INTO sequences VALUES (1, 4, 1, 3);
INSERT INTO sequences VALUES (2, 1, 5, 7);
INSERT INTO sequences VALUES (2, 2, 6, 8);

CREATE OR ALTER PROCEDURE recurse_sequence(seq_id INTEGER)
RETURNS (id_type, item_id INTEGER) AS
BEGIN
FOR SELECT id_type, item_id
FROM sequences s
WHERE s.seq_id = :seq_id
ORDER BY seq_prog
INTO id_type, item_id DO
IF (id_type = 0) THEN -- this means a subsequence
FOR SELECT id_type, item_id
FROM recurse_sequence(:item_id)
INTO id_type, item_id DO
SUSPEND;
ELSE
SUSPEND;
END
^

SELECT id_type, item_id FROM recurse_sequence(1);

1, 1
1, 2
5, 7
6, 8
1, 3

hth,
ciao, lele.