插入查询不在存储过程中工作

时间:2013-07-07 20:14:24

标签: mysql stored-procedures

我有一个更新查询,在隔离运行时有效,但在存储过程中调用时会抱怨。

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定义更新查询,但结果是相同的。有没有人知道发生了什么,我怎么能让我的程序工作?

1 个答案:

答案 0 :(得分: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`)

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