MySQL Case

MySQL Case

MySQL Case syntax and example.

MySQL CASE syntax

CASE case_value
WHEN when_value THEN statement_list
[WHEN when_value THEN statement_list] …
[ELSE statement_list]
END CASE

CASE
WHEN search_condition THEN statement_list
[WHEN search_condition THEN statement_list] …
[ELSE statement_list]
END CASE

Case example

CREATE OR REPLACE FUNCTION
case_test(p_id int)
RETURNS TEXT
BEGIN
DECLARE v_name TEXT;
	CASE p_id
		WHEN 1 THEN SET v_name='One';
		WHEN 2 THEN SET v_name='Two';
	ELSE
		SET v_name='N/A';
	END CASE;
RETURN v_name;
END;

SELECT case_test(1);

Output

FUNCTION CASE_TEST compiled.
One