use test; delimiter // drop function if exists test_fcn; create function test_fcn(p_id bigint unsigned) returns text begin declare done boolean default false; declare first boolean default true; declare return_value text default ''; declare id_ bigint unsigned default null; declare product_ varchar(255); declare cursor_ cursor for select id, product from test.tbl where id < p_id order by id limit 100; declare continue handler for sqlstate '02000' set done = true; open cursor_; lp: loop fetch cursor_ into id_, product_; if done then leave lp; end if; if first then # PROBLEM LINE set return_value = product_; #A #set return_value = concat(return_value, product_); #B set first = false; else set return_value = concat(return_value, '|', product_); end if; end loop; close cursor_; return return_value; end; // delimiter ;