如何在Trigger MYSQL中将变量设置为存储过程的结果?

时间:2016-08-18 23:51:43

标签: mysql database stored-procedures triggers

我在这里遇到一些问题,我正在为我的数据库工作触发,但我不知道如何在触发器中使用存储过程,我想保存过程的结果在一个变量中然后在IF比较器上使用该变量,这是我的代码:

DELIMITER @
CREATE TRIGGER insert_players AFTER INSERT ON players FOR EACH ROW
BEGIN
DECLARE A varchar(50);
set A = CALL consult_sex(player_name); //I WANT SOMETHING LIKE THIS
IF A != FEMALE THEN
INSERT INTO males (id_player, player_fullname, player_celphone)
VALUES (new.id_player, concat(new.player_name, " ", new.player_lastname), new.player_phone);
END IF; 
END;
@

有人可以帮我解决这个疑问吗?会很棒,谢谢。

2 个答案:

答案 0 :(得分:1)

让您的程序采用OUT参数,例如

CREATE PROCEDURE consult_sex(player_name VARCHAR(20), OUT player_sex VARCHAR(10))

在您的程序SET中使用

之类的值
SET player_sex = <your query to get sex>

调用您的过程传递参数

call consult_sex(player_name, @out_value);
select @out_value;

答案 1 :(得分:1)

如果您希望存储例程返回值,则需要存储函数而不是存储过程。使用存储函数,语句如下:

SET A = consult_sex(player_name);

这是一个虚拟函数:

CREATE FUNCTION `consult_sex`(player_name VARCHAR(100)) RETURNS VARCHAR(6) CHARSET utf8
BEGIN

    DECLARE v_sex VARCHAR(6);

    -- Randomly generate one of two values, MALE or FEMALE
    SET v_sex = (SELECT CASE FLOOR(1 + RAND() * (3-1)) WHEN 1 THEN 'MALE' ELSE 'FEMALE' END);

    RETURN v_sex;
END

您提供的触发器代码存在一些语法错误。鉴于表名和列名是正确的,这将适用于存储的函数:

DELIMITER @
CREATE TRIGGER insert_players AFTER INSERT ON players FOR EACH ROW
BEGIN
    DECLARE A VARCHAR(50);
    SET A = consult_sex(NEW.player_name); 
    IF A != 'FEMALE' THEN
        INSERT INTO males (id_player, player_fullname, player_celphone)
        VALUES (NEW.id_player, CONCAT(NEW.player_name, ' ', NEW.player_lastname), NEW.player_phone);
    END IF; 
END;
@

请务必仔细检查player_celphone列的拼写。