MySQL if case語句使用總結

2021-07-30 09:20:37 字數 2652 閱讀 8818

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<90 and stu_grade>=80 then

select stu_grade,'b';

elseif stu_grade<80 and 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等也是相同的。

C if語句 使用if語句

c 的if語句是用來判定所給的條件是否滿足,並根據判斷的結果true或false決定執行哪一步。單個if語句 如 if x y if 表示式 語句1 else 語句2 如 if x y else if 表示式1 語句1 else if 表示式2 語句2 else if 表示式3 語句3 else i...

使用select into 語句

在新建臨時表時,如果一次性插入資料量很大,那麼可以使用select into代替create table,避免log,提高速度 如果資料量不大,為了緩和系統表的資源,建議先create table,然後insert。語法 select column name s into newtable in e...

oralce if語句使用

if語句的使用 a.基本的if條件語句 基本語法 if then end if 或 if a then endif example sql set serveroutput on sql declare x number 3 9 begin if x 10 then dbms output.put ...