My problem is fairly simple. I have table sets
that store product sets (more products looking like one on the outside - computer, mouse and keyboard for ex.) it's connected M:N using sets_products
table to products
table. Each product can have parameters (connected again M:N).
I have a procedure, that generates all parameters as string (for search cache - like 'hdd:120GB, LCD:1440:900, ..'), but now I need to loop through the set's products and call the procedure for each of them. I CAN'T DO IT IN PHP, because this is used in trigger.
I'd like to use something like this (pseudo SQL)
FOREACH(SELECT products_id FROM sets_products WHERE set_id = 1) generate_parameter_list(product_id,@result) @param = CONCAT(@param,",",@result); END FOREACH;
Can this be done in MySQL or not?
foreach() acts on server side only, and does not require shell access nor the mysql command line client, although it may be spawned from within the mysql client. foreach() accepts several types of collections. They are automatically recognized by their pattern.
Using LEAVE statement in loopsThe LEAVE statement allows you to terminate a loop. The general syntax for the LEAVE statement when using in the LOOP , REPEAT and WHILE statements. The LEAVE causes the current loop specified by the label to be terminated.
The MySQL stored program language offers three types of loops : Simple loops using the LOOP and END LOOP clauses. Loops that continue while a condition is true, using the WHILE and END WHILE clauses. Loops that continue until a condition is true, using the REPEAT and UNTIL clauses.
Here's the mysql reference for cursors. So I'm guessing it's something like this:
DECLARE done INT DEFAULT 0; DECLARE products_id INT; DECLARE result varchar(4000); DECLARE cur1 CURSOR FOR SELECT products_id FROM sets_products WHERE set_id = 1; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; OPEN cur1; REPEAT FETCH cur1 INTO products_id; IF NOT done THEN CALL generate_parameter_list(@product_id, @result); SET param = param + "," + result; -- not sure on this syntax END IF; UNTIL done END REPEAT; CLOSE cur1; -- now trim off the trailing , if desired
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With