0

我有一个更新查询,它在单独运行时有效,但在存储过程中调用时会报错。

mysql> UPDATE `user` SET `password`=COALESCE(NULL, `password`) WHERE `id`=1;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 1  Changed: 0  Warnings: 0


mysql> CALL updateUser(1, NULL, NULL, '1950-02-05', NULL);
ERROR 1048 (23000): Column 'male' cannot be null

这是存储过程

DELIMITER $$
CREATE PROCEDURE `updateUser` (IN userId varchar(255), IN password varchar(100), IN male tinyint(1), IN birthday datetime, IN fbId varchar(160))
BEGIN
    START TRANSACTION;
        UPDATE `user` SET `male` = IFNULL(male, `male`), `password` = IFNULL(password, `password`), `birthday` = IFNULL(birthday, `birthday`) WHERE `id` = userId;

        IF fbId IS NOT NULL THEN
            ...
        END IF;
    COMMIT;
END

我也尝试过使用 COALESCE 而不是 IFNULL 来定义更新查询,但结果是一样的。有没有人知道发生了什么以及我怎样才能让我的程序正常工作?

4

1 回答 1

0

问题是存储过程参数与列的名称相同。试试这个:

DELIMITER $$
CREATE PROCEDURE `updateUser` (IN p_userId varchar(255),
                               IN p_password varchar(100),
                               IN p_male tinyint(1),
                               IN p_birthday datetime,
                               IN p_fbId varchar(160))
BEGIN
    START TRANSACTION;
        UPDATE `user` SET `male` = IFNULL(p_male, `male`),
                          `password` = IFNULL(p_password, `password`),
                          `birthday` = IFNULL(p_birthday, `birthday`)
        WHERE `id` = p_userId;

        IF fbId IS NOT NULL THEN
            ...
        END IF;
    COMMIT;
END

您收到关于male不接受 NULL 值的错误,因为表达式:

coalesce(male, `male`)

两次都引用存储过程参数而不是表中的列。

于 2013-07-07T20:59:53.417 回答