如何在MYSQL中编写嵌套if else

时间:2014-02-10 11:41:52

标签: mysql if-statement nested-if

下面的sntax接缝是正确的。在mysql上运行时会出错

  

错误代码:1064。您的SQL语法有错误;检查与MySQL服务器版本对应的手册,以便在第27行“'附近使用正确的语法。

delimiter $$
    create function check2_login(p_username varchar(30),p_password varchar(30),role     varchar(20))
    returns bool
    deterministic 
    begin 
declare loginstatus bool default false;

if role="customer"then 
    select custid from customer where custid=p_username and pwd=p_password;
    if !row_count()=0 then
    select true into loginstatus;
    end if;
else if role="executive"then 
    select execid from executive where execid=p_username and pwd=p_password;
   if !row_count()=0 then
   select true into loginstatus;
    end if;
else if role="admin"then 
    select empid from employee where empid=p_username and pwd=p_password;
    if !row_count()=0 then
    select true into loginstatus;
    end if;
else
   return loginstatus;
end if;
  return loginstatus;
end $$

3 个答案:

答案 0 :(得分:13)

按如下所示更新存储的功能

DELIMITER $$
DROP FUNCTION IF EXISTS `check2_login`$$
CREATE  FUNCTION `check2_login`(p_username VARCHAR(30),p_password VARCHAR(30),role VARCHAR(20)) RETURNS BOOL
    BEGIN
    DECLARE retval INT;
            IF role = "customer" THEN
                SELECT COUNT(custid) INTO retval FROM customer WHERE custid = p_username and pwd = p_password;
                IF retval != 0 THEN
                    RETURN TRUE;    
                ELSE
                    RETURN FALSE;                           
                END IF;
            ELSEIF role = "executive" THEN
                SELECT COUNT(execid) INTO retval FROM executive WHERE execid = p_username and pwd = p_password;
                IF retval != 0 THEN
                    RETURN TRUE;    
                ELSE
                    RETURN FALSE;                           
                END IF;
            ELSEIF role = "admin" THEN
                SELECT COUNT(empid) INTO retval FROM employee WHERE empid = p_username and pwd = p_password;
                IF retval != 0 THEN
                    RETURN TRUE;    
                ELSE
                    RETURN FALSE;                           
                END IF;
            ELSE
                RETURN FALSE;       
            END IF;
    END$$
DELIMITER ;

希望这会对你有帮助......!

答案 1 :(得分:4)

SELECT *, 
   IF(discount='0',
      ( IF(tax='0', discount_price, discount_price + (discount_price * (tax_rate/100))) ),
      ( IF(tax='0', price, price + (price * (tax_rate/100))) )
   ) AS price_last
FROM products WHERE id=1

答案 2 :(得分:2)

我想也许你应该对这个程序使用CASE语句