dynamic query in loop getting wrong value
Please help, this is driving me crazy! When I run the following script and the catid_from is less than catid_to, everything works perfectly. However, when catid_from is greater, the wrong value is used in the update statement. What happens is that all the update statements get run with the last order_to value that the loop sees. Whats even weirder to me is that the order_from values work right. I had a putline statement in the script to ensure that the values where what I thought that they would be and they were. If I have to do it another way, thats fine, but why does it always work one way and never the other when both ways are doing the same processing?
I'll go ahead and post the whole script to make sure I don't leave anything out.
create or replace package body move_cat_order is
procedure reorder(catid_from in number, catid_to in number)
is
var_order_from number := 0;
var_order_to number := 0;
counter number := 0;
type my_rec is record (
from_order number,
to_order number);
type my_table_type is table of my_rec
index by binary_integer;
my_table my_table_type;
i integer := 1;
begin
select order_num into var_order_from from catagories where catid = catid_from;
select order_num into var_order_to from catagories where catid = catid_to;
if var_order_from > var_order_to then
for counter in (var_order_to) .. (var_order_from - 1) loop
my_table(i).from_order := counter;
my_table(i).to_order := counter + 1;
i := i + 1;
end loop;
if my_table.exists(1) then
for i in my_table.first .. my_table.last loop
update catagories set order_num = my_table(i).to_order where order_num = my_table(i).from_order;
end loop;
end if;
update catagories set order_num = var_order_to where catid = catid_from;
end if;
if var_order_from < var_order_to then
for counter in (var_order_from + 1) .. (var_order_to) loop
my_table(i).from_order := counter;
my_table(i).to_order := counter - 1;
i := i + 1;
end loop;
if my_table.exists(1) then
for i in my_table.first .. my_table.last loop
update catagories set order_num = my_table(i).to_order where order_num = my_table(i).from_order;
end loop;
end if;
update catagories set order_num = var_order_to where catid = catid_from;
end if;
end;
end;
Any and all help is greatly appreciated.
Justin