2013-04-23 143 views
2

我正在学习有关MySQL(5.5)中的存储过程,并且在这里想到了使用sprocs可以完成的工作。如何循环遍历结果?

基本数据如下:

select * from fruit; 

name | variety | price | quantity 
--------------------------------- 
Pear Comice - 15 - 2 
Pear Barlett - 20 - 3 
Pear Anjou - 20 - 3 
Apple Red - 10 - 7 
etc 

我如何得到所有类型的水果,说的合并货币价值,所有的梨类型?

我得到尽可能使这个存储过程将得到一个单一品种的水果价值。

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); 
从我的基础数据

所以你看,如果没有增值税应该回来与总150,并与增值税180

我有另一个存储过程,其通过某种方式的结果集循环? 解决这个问题的最好方法是什么,以便这个计算停留在数据库服务器上? 这是游标将被使用的地方吗?

我读很多关于何时/不使用存储过程,但我对此已经警告我,他们在很大程度上依赖于他们已经是一个公司的面试。

编辑 - 为了澄清我的整体问题。

我如何从我这里得到:

CALL getStockValue('Comice',1,@tot); 
// gives 36 

(在事后应该改名getStockValueByVariety())

的地方,我想:

CALL getStockValueByName('Pear',1,@tot); 
// gives 180 - because it gets ALL Pear types, not just the variety Comice 

FINALLY - 突然意识到,我是缺少一个GROUP BY ...

SELECT SUM(price*quantity) as tot 
FROM fruit 
WHERE name = 'Pear' 
GROUP BY name; 

回答

5

使用CASE语句,只是从存储过程返回值。

SELECT 
    CASE vat 
     WHEN 1 THEN (((quantity*price)*20/100) + (quantity * price)) 
     ELSE (quantity*price) 
    END AS nett_value 
FROM fruit; 

如果你想总和所有的特殊品种,那么概括

SELECT 
    SUM(CASE vat 
     WHEN 1 THEN (((quantity*price)*20/100) + (quantity * price)) 
     ELSE (quantity*price) 
    END) AS tot 
FROM fruit 
WHERE variety = @variety 
GROUP BY 
    name 
+0

THX对于这一点,我接受你的改进语法,但我已经附加在编辑我原来的问题试图澄清我的总体目标。 – Cups 2013-04-24 08:07:39

+0

我的不好:“select SUM(price * quantity)as fruit from tot where name ='Pear'GROUP BY name;”是我应该去的地方。 – Cups 2013-04-24 08:39:38