Wednesday, 14 August 2013

Combine results from a procedure looped select statement in MySQL?

Combine results from a procedure looped select statement in MySQL?

I've been trying to combine the results of these select statements using
subqueries, views and temporary tables:
CREATE PROCEDURE PERCOSTCENTER()
BEGIN
DECLARE i INT DEFAULT 0;
DECLARE n INT DEFAULT 0;
SET n = (SELECT count(*) FROM swyta01.lov_cost_center);
SET i = 1;
WHILE i <= n DO
SELECT a.DESCRIPTION, COUNT(b.ID_EMP) from
swyta01.lov_cost_center as a, swyta01.employee as b
WHERE b.ID_COST_CENTER = i AND a.ID_COST_CENTER = i;
SET i = i + 1;
END WHILE;
END;
;;
The problem with subqueries is that I cannot put the super select outside
of the while loop like this: select * from (while i <= ... (select ... )
The same goes for views; they cannot be put outside the while loop.
As for the temp tables, I tried the approach but as the query executes,
each select statement in the loop renders its own view (I'm using
Workbench BTW), and I don't want this to happen (imagine if n = 1000!)
Another approach that I thought of was to use UNION but lo, It cannot be
put at the end of the while loop like this: while ... select ... UNION ...
end while
Any ideas? Thanks!

No comments:

Post a Comment