2009-07-15 86 views
0

。由此我給存儲過程 「GetAvgOut」:調用存儲過程的輸出參數

delimiter // 
DROP PROCEDURE IF EXISTS GetAvgOut// 
CREATE DEFINER = 'MailIntimator'@'127.0.0.1' PROCEDURE GetAvgOut(OUT average INT,IN col VARCHAR(30),IN tbl VARCHAR(30)) 
READS SQL DATA 
COMMENT 'returns average' 
BEGIN 
SET @userVar = CONCAT(' SELECT AVG(' , col , ') FROM ' , tbl); 
PREPARE stmt FROM @userVar; 
EXECUTE stmt; 
END; 
// 
delimiter ; 

我打過電話使用aforeseen程序,

CALL GetAvgOut(@a,'Population','city'); 
SELECT @a; 

「選擇@a」 返回null。我怎樣才能得到分配給參數「@a」的平均值?

+0

爲什麼average聲明爲int,而不是float字段類型? – 2009-07-15 08:18:31

+0

嘗試: CALL GetAvgOut(@ average,'Population','city'); SELECT @average; – 2009-07-15 08:20:25

回答

1

我不是mysql專家,但是您是否需要在任何時候引用OUT變量併爲其賦值?

例如作爲上看到http://dev.mysql.com/doc/refman/5.0/en/call.html

CREATE PROCEDURE p (OUT ver_param VARCHAR(25), INOUT incr_param INT) 
BEGIN 
    # Set value of OUT parameter 
    SELECT VERSION() INTO ver_param; 
    # Increment value of INOUT parameter 
    SET incr_param = incr_param + 1; 
END; 

HTH

菲爾

1

你不設置您的選擇OUT參數。

嘗試更新聲明:

SET @userVar = CONCAT('SELECT AVG(' , col , ') INTO average FROM ' , tbl); 
0

正如@Philip提到的,你需要設置輸出變量的值。結合@Josh's和@ Philip的答案給出了類似這樣的東西

BEGIN 
    SET @userVar = CONCAT(' SELECT AVG(' , col , ') into @average FROM ' , tbl , ' '); 
    PREPARE stmt FROM @userVar; 
    EXECUTE stmt; 
    set average = @average; 
END