views:

354

answers:

2

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;
+2  A: 

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
Rory
Lovely. Would you please bother writing a short example for my usage?
Tomáš Fejfar
Thanks a lot. I'll try this...
Tomáš Fejfar
I needed to use CALL procedure_name and DECLARE every parameter used, but it worked. Thanks a lot.
Tomáš Fejfar
+1  A: 

This can be done with MySQL, although it's highly unintuitive:

CREATE PROCEDURE p25 (OUT return_val INT)
BEGIN
  DECLARE a,b INT;
  DECLARE cur_1 CURSOR FOR SELECT s1 FROM t;
  DECLARE CONTINUE HANDLER FOR NOT FOUND
  SET b = 1;
  OPEN cur_1;
  REPEAT
    FETCH cur_1 INTO a;
    UNTIL b = 1
  END REPEAT;
  CLOSE cur_1;
  SET return_val = a;
END;//

Check out this guide: http://dev.mysql.com/tech-resources/articles/mysql-storedprocedures.pdf

Max Toro