您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

MySQL中的if和case语句使用总结

2024/3/18 18:03:30发布21次查看
mysql的if既可以作为表达式用,也可在存储过程中作为流程控制语句使用,如下是做为表达式使用: if表达式 代码如下: if(expr1,expr2,expr3) 如果 expr1 是true (expr1 0 and expr1 null),则 if()的返回值为expr2; 否则返回值则为 expr3。if() 的返回值为数
mysql的if既可以作为表达式用,也可在存储过程中作为流程控制语句使用,如下是做为表达式使用:
if表达式
代码如下:
if(expr1,expr2,expr3)
如果 expr1 是true (expr1 0 and expr1 null),则 if()的返回值为expr2; 否则返回值则为 expr3。if() 的返回值为数字值或字符串值,具体情况视其所在语境而定。
代码如下:
select *,if(sva=1,男,女) as ssva from taname where sva !=
作为表达式的if也可以用case when来实现:
代码如下:
select case sva when 1 then '男' else '女' end as ssva from taname where sva != ''
在第一个方案的返回结果中, value=compare-value。而第二个方案的返回结果是第一种情况的真实结果。如果没有匹配的结果值,则返回结果为else后的结果,如果没有else 部分,则返回值为 null。
例如:
代码如下:
select case 1 when 1 then 'one'
  when 2 then 'two' 
   else 'more' end
as testcol
将输出one
ifnull(expr1,expr2)
假如expr1 不为 null,则 ifnull() 的返回值为 expr1; 否则其返回值为 expr2。ifnull()的返回值是数字或是字符串,具体情况取决于其所使用的语境。
代码如下:
mysql> select ifnull(1,0);
        -> 1
mysql> select ifnull(null,10);
        -> 10
mysql> select ifnull(1/0,10);
        -> 10
mysql> select ifnull(1/0,'yes');
        -> 'yes'
ifnull(expr1,expr2) 的默认结果值为两个表达式中更加“通用”的一个,顺序为string、 real或 integer。
if else 做为流程控制语句使用
if实现条件判断,满足不同条件执行不同的操作,这个我们只要学编程的都知道if的作用了,下面我们来看看mysql 存储过程中的if是如何使用的吧。
代码如下:
if search_condition then 
    statement_list  
[elseif search_condition then]  
    statement_list ...  
[else 
    statement_list]  
end if
与php中的if语句类似,当if中条件search_condition成立时,执行then后的statement_list语句,否则判断elseif中的条件,成立则执行其后的statement_list语句,否则继续判断其他分支。当所有分支的条件均不成立时,执行else分支。search_condition是一个条件表达式,可以由“=、、>=、!=”等条件运算符组成,并且可以使用and、or、not对多个表达式进行组合。
例如,建立一个存储过程,该存储过程通过学生学号(student_no)和课程编号(course_no)查询其成绩(grade),返回成绩和成绩的等级,,成绩大于90分的为a级,小于90分大于等于80分的为b级,小于80分大于等于70分的为c级,依次到e级。那么,创建存储过程的代码如下:
代码如下:
create procedure dbname.proc_getgrade  
(stu_no varchar(20),cour_no varchar(10))  
begin 
declare stu_grade float;  
select grade into stu_grade from grade where student_no=stu_no and course_no=cour_no;  
if stu_grade>=90 then 
    select stu_grade,'a';  
elseif stu_grade=80 then 
    select stu_grade,'b';  
elseif stu_grade=70 then 
    select stu_grade,'c';  
elseif stu_grade70 and stu_grade>=60 then 
    select stu_grade,'d';  
else 
    select stu_grade,'e';  
end if;  
end
注意:if作为一条语句,在end if后需要加上分号“;”以表示语句结束,其他语句如case、loop等也是相同的。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product