I have a stored procedure like so:
$connection->query('
drop procedure if exists listing_count;
create procedure listing_count(IN parent int(11))
begin
declare count1 int(11) default 0;
declare count2 int(11) default 1;
create temporary table ids as (select id from category where id=parent);
while count1<>count2 do
set count1=(select count(id) from ids);
insert into ids(id) select id from category where id not in(select id from ids) and related in(select id from ids);
set count2=(select count(id) from ids);
end while;
(select count(*) from listing_category where category in(select id from ids));
end');
$fetch=$connection->query('select *,listing_count(id) as listing_count from category')->fetchall(pdo::FETCH_UNIQUE|pdo::FETCH_ASSOC);
I would like to use my procedure like a function. So that listing_count
gets the count so that I can use it. Do I need to create a separate function? Can a procedure get my count and return it?
Turning it into a function like so:
drop function if exists listing_count;
create function listing_count(parent int(11)) returns int(11) deterministic
begin
declare count1 int(11) default 0;
declare count2 int(11) default 1;
create temporary table ids as (select id from category where id=parent);
while count1<>count2 do
set count1=(select count(id) from ids);
insert into ids(id) select id from category where id not in(select id from ids) and related in(select id from ids);
set count2=(select count(id) from ids);
end while;
return (select count(*) from listing_category where category in(select id from ids));
end
But this does not work. I am not very familiar with procedures vs functions but I assume that I can't add all the functionality into a function as I can in a procedure.