Subject | Re: [ib-support] SPs and recursion |
---|---|

Author | Nando Dessena |

Post date | 2003-02-20T21:04:11Z |

Duilio,

dili> this is a recursive SP I found in the net:

<SNIP>

Honestly, it does not strike me as an example of how to write one...

dili> In order to understand better how SPs work, I tried to modify the

dili> code, so to get

dili> 5

dili> 20

dili> 60

dili> 120

dili> i.e. to have the result returned at every call.

This is not the way it works; the partial results are 1, 2, 6, 24,

120. Here is your original procedure a little reworked to accomplish

the task:

CREATE PROCEDURE FACTORIAL(NUM INTEGER)

RETURNS (N_FACTORIAL NUMERIC(18, 0))

AS

BEGIN

if (num = 1) THEN

n_factorial = 1;

ELSE BEGIN

for select n_factorial from FACTORIAL(:num - 1) into :n_factorial do begin

suspend;

n_factorial = :n_factorial * :num;

end

END

SUSPEND;

END

I'm sure others on this list can do better, though.

dili> PS temporary tables make a too easy solution...

And unneeded, too.

Ciao

--

Nando mailto:nandod@...

dili> this is a recursive SP I found in the net:

<SNIP>

Honestly, it does not strike me as an example of how to write one...

dili> In order to understand better how SPs work, I tried to modify the

dili> code, so to get

dili> 5

dili> 20

dili> 60

dili> 120

dili> i.e. to have the result returned at every call.

This is not the way it works; the partial results are 1, 2, 6, 24,

120. Here is your original procedure a little reworked to accomplish

the task:

CREATE PROCEDURE FACTORIAL(NUM INTEGER)

RETURNS (N_FACTORIAL NUMERIC(18, 0))

AS

BEGIN

if (num = 1) THEN

n_factorial = 1;

ELSE BEGIN

for select n_factorial from FACTORIAL(:num - 1) into :n_factorial do begin

suspend;

n_factorial = :n_factorial * :num;

end

END

SUSPEND;

END

I'm sure others on this list can do better, though.

dili> PS temporary tables make a too easy solution...

And unneeded, too.

Ciao

--

Nando mailto:nandod@...