Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to loop through results in an sproc?
    primarykey
    data
    text
    <p>I'm learning about stored procedures in mysql (5.5), and have hit a bit of a mental block here about what can be done using sprocs.</p> <p>The base data looks like this:</p> <pre><code>select * from fruit; name | variety | price | quantity --------------------------------- Pear Comice - 15 - 2 Pear Barlett - 20 - 3 Pear Anjou - 20 - 3 Apple Red - 10 - 7 etc </code></pre> <p>How do I get the combined monetary value of ALL types of a fruit, say, all Pear types?</p> <p>I got as far as making this sproc which will get the value of a single variety of a fruit.</p> <pre><code>DROP PROCEDURE IF EXISTS getStockValue; DELIMITER // CREATE PROCEDURE `getStockValue`( IN variety varchar(20), IN vat BOOLEAN, OUT tot DECIMAL(8,2) ) BEGIN DECLARE nett_value INT; SELECT (quantity*price) INTO nett_value from fruit where variety = variety; IF vat = 1 THEN SELECT (nett_value*20/100)+(nett_value) INTO tot; ELSE SELECT nett_value INTO tot; END IF; SELECT tot; END;// DELIMITER ; CALL getStockValue('Comice',1,@tot); </code></pre> <p>So from my base data you see that without VAT it should come back with the total 150, and with VAT 180.</p> <p>Do I have another sproc which loops through a result set somehow? What is the best way to tackle this so that this computation stays on the database server? Is this where a cursor would be used?</p> <p>I've read an awful lot about when to/not to use sprocs, but I have an interview with a company that have warned me they rely heavily on them already.</p> <p><strong>EDIT</strong> - in order to clarify my overall question.</p> <p>How do I get from where I am:</p> <pre><code>CALL getStockValue('Comice',1,@tot); // gives 36 </code></pre> <p>(in hindsight should be renamed getStockValueByVariety())</p> <p>To where I want to be:</p> <pre><code>CALL getStockValueByName('Pear',1,@tot); // gives 180 - because it gets ALL Pear types, not just the variety Comice </code></pre> <p><strong>FINALLY</strong> - twigged, I was missing a GROUP BY ...</p> <pre><code>SELECT SUM(price*quantity) as tot FROM fruit WHERE name = 'Pear' GROUP BY name; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload