在存储过程中使用变量

时间:2012-09-14 10:27:25

标签: mysql stored-procedures

试图弄清楚为什么它是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
    -> //

1 个答案:

答案 0 :(得分:2)

您应该使用INOUT参数 -

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

示例:

当@total值为0时(0 in,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 |
+--------------+