2012-09-14 152 views
0

試圖找出它爲什麼是NULL。我期待7印。在存儲過程中使用變量

mysql> set @total = 0; 
Query OK, 0 rows affected (0.00 sec) 

mysql> call getAuthorCount(@total); 
+------------------------+ 
| count(distinct author) | 
+------------------------+ 
|      7 | 
+------------------------+ 
1 row in set (0.00 sec) 

Query OK, 0 rows affected (0.02 sec) 

mysql> select @total as totalauthors; 
+--------------+ 
| totalauthors | 
+--------------+ 
|   NULL | 
+--------------+ 

的過程,

mysql> create procedure getAuthorCount(out authorcount int) 
    -> begin 
    -> select count(distinct author) from libbooks; 
    -> end 
    -> // 
+0

請出示完整的代碼。 – Devart

+0

@Devart:我已更新信息 – John

回答

2

應該使用INOUT參數 -

CREATE PROCEDURE getAuthorCount(INOUT authorcount INT) 
BEGIN 
    SELECT count(DISTINCT author) FROM libbooks; 
END 

實例:

當@total值作爲是(0在,0 out):

DROP PROCEDURE getAuthorCount; 
DELIMITER $$ 
CREATE PROCEDURE getAuthorCount(INOUT authorcount INT) 
BEGIN 
    -- SET authorcount = 100; 
END$$ 
DELIMITER ; 

SET @total = 0; 
CALL getAuthorCount(@total); 
SELECT @total AS totalauthors; 
+--------------+ 
| totalauthors | 
+--------------+ 
|   0 | 
+--------------+ 

當@total值替換存儲過程中新的價值:

DROP PROCEDURE getAuthorCount; 
DELIMITER $$ 
CREATE PROCEDURE getAuthorCount(OUT authorcount INT) 
BEGIN 
    SET authorcount = 100; 
END$$ 
DELIMITER ; 

SET @total = 0; 
CALL getAuthorCount(@total); 
SELECT @total AS totalauthors; 
+--------------+ 
| totalauthors | 
+--------------+ 
|   100 | 
+--------------+ 
+0

謝謝。但我讀了'存儲過程可以改變這個(OUT)參數並傳回給調用程序。' – John

+0

爲什麼我需要使用IN或INOUT當我不打算髮送一個值 – John

+0

因爲參數OUT authorcount = NULL默認情況下,你應該設置新的值,例如'SET authorcount = 100'在程序的主體中。 – Devart