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
    -> //
4

1 回答 1

2

您应该使用 INOUT 参数 -

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

例子:

当@total 值保持原样时(0 输入,0 输出):

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 |
+--------------+
于 2012-09-14T11:18:56.850 回答