mysqlif-statementmysql-variables

Run different SQL statements using If Then with a variable


Trying to do something very simple. Using If/Then, is there a way to run a separate Select statement based on the value of a variable? The function GetTotalActiveUnits() in the below code returns an integer.

    set @RetVal =  GetTotalActiveUnits(CustomerCode);
    if  @RetVal = 0 then 
    Select * from tblREF_UnitInfo;
    else
    select * from tblREF_State;
    end if

Solution

  • There is no problem with your code - at least as far as IF is concerned and if it is in a stored routine.

    drop procedure if exists p;
    delimiter $$
    create procedure p(inp int)
    begin
         set @RetVal = inp;# GetTotalActiveUnits(CustomerCode);
        if  @RetVal = 0 then 
         select @retval ;
        else
         select @retval ;
        end if ;
    
    end $$
    
    delimiter ;
    
    call p(1);
    +---------+
    | @retval |
    +---------+
    |       1 |
    +---------+
    1 row in set (0.001 sec)
    
    call p(0)
    +---------+
    | @retval |
    +---------+
    |       0 |
    +---------+
    1 row in set (0.001 sec)