Subject Re: [ib-support] Breaking out of For Select...Do
Author Lucas Franzen
Joe,


> The table has the following values for THIS_NUM:
> 100
> 300
> 200
> 800
> 150
>
> I want to loop through these rows.
>
> 1st iteration: MY_NUM = 100, THE_TOTAL = 100
> 2nd iteration: MY_NUM = 300, THE_TOTAL = 400
> 3rd iteration: MY_NUM = 200, THE_TOTAL = 600
>
> At this point, THE_TOTAL is over 500, so I'm done. I don't even want to
> loop through the 4th and 5th rows.

If you want to end the loop AND the procedure you can use EXIT:


for select MY_NUM from MY_TABLE into :THIS_NUM
do
BEGIN
THE_TOTAL = THE_TOTAL + THIS_NUM;
if (THE_TOTAL >= 500) then
begin
SUSPEND; /* if needed */
EXIT;
end
END


If you want to continue with your procedure after the FOR..SELECT loop
than the answer is: you can't. There is no BREAK statement.

What you can do in that case is:

declare variable sum_ok CHAR(1);

sum_ok ='0';
for select MY_NUM from MY_TABLE into :THIS_NUM
do
BEGIN
if ( sum_ok = '0' ) then THE_TOTAL = THE_TOTAL + THIS_NUM;
if (THE_TOTAL >= 500) then
begin
sum_ok = '1';
end
END

this will prevent from further adding, BUT the 4th, 5th...nth record
will be retrieved.

So if you need it as a real break-statement it should be the easiest way
to:
- write a procedure that does use EXIT (as shown above)
- call this procedure from your procedure.

HTH

Luc.