IF语句主要有以下三种基本形式:
一、 IF-THEN语句
IF CONDITION THEN
STATEMENT 1;
...
STATEMENT N;
END IF;
二、 IF-THEN-ELSE语句
IF CONDITION THEN
STATEMENT 1;
ELSE
STATEMENT 2;
END IF;
三、 ELSLF语句
IF CONDITION 1 THEN
STATEMENT 1;
ELSIF CONDITION 2 THEN
STATEMENT 2;
ELSIF CONDITION 3 THEN
STATEMENT 3;
...
ELSE
STATEMENT N; -->>在ELSIF语句中,ELSE子句并不是必需的
END IF
下面,试举一例:用SYSDATE函数判断今天是否是周末,如果是周末的话,判断现在是上午还是下午。无论是否是周末,最后均显示日期。
注意:IF的嵌套用法和在ELSIF语句中,ELSE子句并不是必需的
DECLARE v_day varchar2(10); v_time number(2); BEGIN v_day := RTRIM(to_char(sysdate,'DAY')); v_time := to_char(sysdate,'hh24'); IF v_day in ('SATURDAY','SUNDAY') THEN -->>下面嵌套了一个ELSIF语句 IF v_time >= 6 AND v_time <12 THEN DBMS_OUTPUT.PUT_LINE('Good Moring'); ELSIF v_time >=12 AND v_time <=18 THEN DBMS_OUTPUT.PUT_LINE('Good Afternoon'); END IF; END IF; DBMS_OUTPUT.PUT_LINE('The time is: '||to_char(sysdate,'yyyy-mm-dd hh24:mi:ss')); END;
CASE语句
CASE语句存在两种形式:CASE和搜索式CASE。
一、 CASE语句
CASE SELECTOR
WHEN EXPRESSION 1 THEN STATEMENT 1;
WHEN EXPRESSION 2 THEN STATEMENT 2;
...
WHEN EXPRESSION N THEN STATEMENT N;
ELSE STATEMENT N+1;
END CASE;
下面,试举一例:用于判断输入数值的奇偶性。
DECLARE v_num NUMBER := &user_num; v_num_flag NUMBER; BEGIN v_num_flag := MOD(v_num,2); CASE v_num_flag WHEN 0 THEN DBMS_OUTPUT.PUT_LINE(v_num||' is even number'); ELSE DBMS_OUTPUT.PUT_LINE(v_num||' is odd number'); END CASE; END;
二、 搜索式CASE语句
CASE
WHEN SEARCH CONDITION 1 THEN STATEMENT 1;
WHEN SEARCH CONDITION 2 THEN STATEMENT 2;
...
WHEN SEARCH CONDITION N THEN STATEMENT N;
ELSE STATEMENT N+1;
END CASE;
以下用搜索式CASE语句重写上例 -->> 注意:没有声明v_num_flag变量,直接在WHEN中判断
DECLARE v_num NUMBER := &user_num; BEGIN CASE WHEN MOD(v_num,2)=0 THEN DBMS_OUTPUT.PUT_LINE(v_num||' is even number'); ELSE DBMS_OUTPUT.PUT_LINE(v_num||' is odd number'); END CASE; END;
CASE表达式
倘若是使用CASE表达式,上述CASE语句和搜索式CASE语句可分别重写如下:
一、 对应CASE语句
DECLARE v_num NUMBER := &user_num; v_num_flag number; v_result varchar2(30); BEGIN v_num_flag := MOD(v_num,2); v_result := CASE v_num_flag WHEN 0 THEN v_num||' is even number' ELSE v_num ||' is odd number' END; DBMS_OUTPUT.PUT_LINE(v_result); END;
二、 对应搜索式CASE语句
DECLARE v_num NUMBER := &user_num; v_result varchar2(30); BEGIN v_result := CASE WHEN MOD(v_num,2) = 0 THEN v_num||' is even number' ELSE v_num ||' is odd number' END; DBMS_OUTPUT.PUT_LINE(v_result); END;
注意:CASE语句和CASE表达式之间的语法区别:在CASE语句中,WHEN和ELSE子句中的可执行语句以分号结尾。而在CASE表达式中,WHEN和ELSE子句所包含的表达式的结尾处不是分号。CASE语句以END CASE终止,CASE表达式以END结尾。
CASE表达式常用于SELECT INTO语句中,试举一例:
DECLARE v_sal_level varchar2(10); v_empno number(4) :=&empno; v_name varchar2(10); BEGIN SELECT ename, CASE WHEN sal >= 3000 THEN 'high' WHEN sal >= 1000 THEN 'medium' ELSE 'low' END INTO v_name,v_sal_level FROM emp WHERE EMPNO = v_empno; DBMS_OUTPUT.PUT_LINE(v_name||' salary is '||v_sal_level); END;