MySQL IF ...然后是Query Statement

时间:2011-04-22 06:47:36

标签: mysql sql stored-functions

这样的东西在MySQL中是有效的:

DELIMITER //
CREATE FUNCTION LOGIN_VALIDATE(IN uName VARCHAR(32),IN uPass VARCHAR(32))
RETURNS BOOLEAN
BEGIN
    DECLARE row_count BOOLEAN DEFAULT 0;
    DECLARE stored_pass VARCHAR(32) DEFAULT NULL;
    DECLARE valid_return BOOLEAN DEFAULT 0;
    SELECT count(*) INTO row_count FROM Login WHERE userId='uName';
    IF row_count = 1 THEN 
        SELECT pWord INTO stored_pass FROM Login WHERE userId='uName';
    END IF;
    IF stored_pass = 'uPass' THEN 
        SET valid_return = 1;
    END IF;
    RETURN valid_return;
END //
DELIMITER ;

1 个答案:

答案 0 :(得分:4)

使用:

DECLARE valid_return BOOLEAN DEFAULT 0;

SELECT CASE WHEN COUNT(*) = 1 THEN 1 ELSE 0 END
  INTO valid_return
  FROM LOGIN l
 WHERE l.userid = @uName
   AND l.pword = @uPass

始终尝试最小化表格上的传递次数以获得所需的结果。 SQL是基于SET的,而不是过程式的 - 当正确接近SQL时,SQL将更适合您。