数据库分支结构

1、if函数

  1. 功能:实现简单的双分支
  2. 语法:if(表达式1,表达式2,表达式3)
  3. 执行顺序,如果表达式1成立(为true),则if函数返回表达式2的值,否则返回表达式1的值
  4. 场所:任何地方

2、case结构

  1. 类似于java中的switch语句,一般用于等值判断
语法
	case 变量|表达式|字段
	when 要判断的值 then 返回的值1或语句1;
	when 要判断的值 then 返回的值2或语句1;
	...
	else 要返回的值n或语句n;
	end case;
  1. 类似于java中多重if语句,一般用于区间判断
语法
	case 
	when 要判断的条件1 then 返回的值1或语句1;
	when 要判断的条件2 then 返回的值2或语句2;
	...
	else 要返回的值n或语句n;
	end case;
  1. 特点:
    (1)可以作为表达式,可以嵌套在其他语句中:放在任何地方
    在这里插入图片描述

(2)作为独立表达式,只能放在begin end中
在这里插入图片描述

(3)when中的值或者条件成立,则执行相应的then后面的语句,并且结束case,如果都不满足,则执行else中的语句或值
(4)else可以省略,如果else省略,并且所有的条件都不满足,则返回null

  1. 案例:
	#创建存储过程,根据传入的成绩,来显示等级:A,B,C,D
	create procedure test_case(in score int)
	begin
		case
		when socre >= 90 and socre <= 100 then select 'A';
		when score >= 80 then select 'B';
		when score >= 70 then select 'C';
		else select 'D';
		end case;
	end $

	#调用存过程
	call test_case(95) $
		

3、循环结构

  1. 场所:begin end中,所以需要依托存储过程或者函数作为载体
  2. 语法
创建:
	create procedure pro_while(in insertCount int)
	begin
		declare i int dafault 1;
		while i <= insertCount do
			insert into admin values('Rose'+i,'666');
			set i = i+1;
			end while;
	end $
调用:
	call pro_while(10) $

猜你喜欢

转载自blog.csdn.net/qq_45151059/article/details/113750492