delimiter // create procedure update_ordinal( in kbase int ) begin declare done int default 0; declare bookids int default 0; declare kds int default 0; declare count int default 0; declare books_cur cursor for select distinct book_id from krecords where kbase_id = kbase group by book_id; declare krecords_cur cursor for select id from krecords where book_id = bookids; declare continue handler for not found set done = 1; open books_cur; while done=0 do fetch books_cur into bookids; if not done then open krecords_cur; set count = 1; while done=0 do fetch krecords_cur into kds; if not done then update krecords set ordinal = count where id= kds; set count = count +1; end if; end while; close krecords_cur; set done = 0; end if; end while; close books_cur; end;// delimiter ; call update_ordinal(1);