MySQL 流程控制语句

/*
	SQL函数以及流程控制实验
	计算 1-n的和
	NonkeyJiang
	2017-09-14
*/
DROP FUNCTION IF EXISTS test_func;
CREATE FUNCTION test_func(num INT)
RETURNS INT
BEGIN
	DECLARE val_sum INT DEFAULT 0;
	DECLARE val_num INT DEFAULT num;
	DECLARE run_state INT;
	SET run_state = 5; -- 切换不同运行状态以测试不同代码段
	
	IF run_state = 1 THEN 
		/*
			LOOP 循环 
			label 不可省略,否则不能退出,LOOP没有自带退出判断,
			只能通过 LEAVE退出所有循环,ITERATE退出此次循环,
			这两个命令对所有类型的循环都适用。
		*/
		label:LOOP	
			IF val_num < 0 THEN
				LEAVE label;
			ELSEIF val_num = 2 THEN
				SET val_num = val_num - 1;
				ITERATE label;
			END IF;
			SET val_sum = val_sum + val_num;
			SET val_num = val_num - 1;
		END LOOP label;

	ELSEIF run_state = 2 THEN -- REPEAT 循环 label2 可以省略,但是添加以便灵活退出。
		label2:REPEAT
			SET val_sum = val_sum + val_num;
			SET val_num = val_num - 1;
		UNTIL val_num < 0 -- 此处不能带分号 ;
		END REPEAT label2;

	ELSEIF run_state = 3 THEN -- WHILE 循环 label3 可以省略,但是添加以便灵活退出。
		label3:WHILE val_num > 0 DO
		SET val_sum = val_sum + val_num;
		SET val_num = val_num - 1;
		END WHILE label3;
			
	ELSEIF run_state = 4 THEN	-- CASE 控制分支例一
		CASE val_num
		WHEN 10 THEN SET val_sum = 100;
		WHEN 20 THEN SET val_sum = 200;
		ELSE SET val_sum = val_num;
		END CASE;
	
	ELSEIF run_state = 5 THEN	-- CASE 控制分支例二
		CASE 
		WHEN val_num >= 10 AND val_num < 20 THEN SET val_sum = 100;
		WHEN val_num > 20 THEN SET val_sum = 200;
		ELSE SET val_sum = val_num;
		END CASE;

	END IF;
	RETURN val_sum;
END; -- END FUNCTION

SELECT test_func(10);

你可能感兴趣的:(mysql,数据库)