如何将查询结果存储到变量中并多次使用?

时间:2016-08-27 23:34:57

标签: mysql sql stored-procedures

我有一个查询(触发器),如下所示:

BEGIN     
    IF (new.edited_id IS NULL) THEN
        IF (SELECT 1 FROM users WHERE id = new.author_id AND IFNULL((active & b'1000000' > 0), 0) < 1) THEN
            SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = "you cannot ask anymore";
        ELSEIF (SELECT 1 FROM users WHERE id = new.author_id AND IFNULL((active & b'10000000' > 0), 0) < 1) THEN
            SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = "you cannot answer anymore";
        END IF;
    ELSE 
        IF (SELECT 1 FROM users WHERE id = new.author_id AND IFNULL((active & b'100000000' > 0), 0) < 1) THEN
            SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = "you cannot edit anymore";
        END IF;
END

如您所见,那些内部IF语句的条件几乎相同。那我该如何改进呢?

我的意思是,如何将以下查询的结果存储到变量中:

SELECT active FROM users WHERE id = new.author_id;

然后将其用于以下条件:

IF (IFNULL((@variable & b'1000000' > 0), 0) < 1) THEN
IF (IFNULL((@variable & b'10000000' > 0), 0) < 1) THEN
IF (IFNULL((@variable & b'100000000' > 0), 0) < 1) THEN

我该如何处理?

1 个答案:

答案 0 :(得分:1)

声明 local variable 并使用select语句的输出设置它。

DECLARE v_active bit(10);
SET v_active := (SELECT active FROM users WHERE id = new.author_id);