Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • "IF ELSE" statement in MySQL

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 327
    Comment on it

    The statement which allows you to execute a set of SQL ststements on the basis of certain conditions is known as MYSQL IF statement.

    Below I am explaining the structure for if-else statement.

    MySQL IF statement syntax-

     IF expression THEN 
           statements;
        END IF;
    

    MySQL IF-ELSE statement syntax-

    IF expression THEN
       statements;
    ELSE
       else-statements;
    END IF;
    

    MySQL IF-ELSE-IF statement syntax-

    IF expression THEN
       statements;
    ELSEIF expression THEN
       statements;
    ...
    ELSE
       statements;
    END IF;
    

    MySQL IF example

    In following example we describe, how to use the IF ESLEIF ELSE statement. The GetCustomerLevel() stored procedure accepts two parameters customer number and customer level.

    First, it gets the credit limit from the customers table.

    Then, based on the credit limit, it determines the customer level: PLATINUM , GOLD , and SILVER .

    The parameter p_customerlevel stores the level of the customer and is used by the calling program.

    DELIMITER $$ 
    
        CREATE PROCEDURE GetCustomerLevel(
            in  p_customerNumber int(11), 
            out p_customerLevel  varchar(10))
        BEGIN
            DECLARE creditlim double;
    
            SELECT creditlimit INTO creditlim
            FROM customers
            WHERE customerNumber = p_customerNumber;
    
            IF creditlim > 50000 THEN
         SET p_customerLevel = 'PLATINUM';
            ELSEIF (creditlim <= 50000 AND creditlim >= 10000) THEN
                SET p_customerLevel = 'GOLD';
            ELSEIF creditlim < 10000 THEN
                SET p_customerLevel = 'SILVER';
            END IF;
    
        END$$
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: