IF and Case statements in MySQL

Tommy02 picture Tommy02 · Dec 26, 2012 · Viewed 9.3k times · Source

I would like to select * if 5 is greater than 2, if false select a particular column. Where am I going wrong?

SELECT IF(5>2, *, column_x),
CASE whereheard_name WHEN 'Newspaper' THEN 'a'
         WHEN 'TV' THEN 'b' 
         WHEN 'Internet' THEN 'c'
         ELSE '-'
    END 
    AS result
FROM whereheard;

Thanks for the answers to the above. Here is the following example stored procedure I am using:

DELIMITER $$

USE `registration`$$

DROP PROCEDURE IF EXISTS `test2`$$

CREATE DEFINER=`root`@`localhost` PROCEDURE `test2`()
BEGIN
    IF(5>2) THEN
            SELECT * FROM whereheard;
        ELSE
            SELECT whereheard_name FROM whereheard;
        END IF;
END$$

DELIMITER ;

This is how I have called it:

CALL test2(),        
CASE whereheard_name WHEN 'Newspaper' THEN 'a'
         WHEN 'TV' THEN 'b' 
         WHEN 'Internet' THEN 'c'
         ELSE '-'
    END 
    AS result
FROM whereheard; 

Where am I going wrong with this?

Answer

a1ex07 picture a1ex07 · Dec 26, 2012

You cannot do it in SQL (I mean particular statement cannot have dynamic number of columns). You can write stored procedure that does the job though :

CREATE PROCEDURE FOO .....
.....
IF (5>2) THEN
 SELECT * FROM ...
ELSE
 SELECT column1 FROM ....
END IF;