Answer: Consider the script created in the section in Chapter 5: SET SERVEROUTPUT ON DECLARE v_day VARCHAR2(15); v_time VARCHAR(8); BEGIN v_day := TO_CHAR(SYSDATE, 'fmDAY'); v_time := TO_CHAR(SYSDATE, 'HH24:MI');
IF v_day IN ('SATURDAY', 'SUNDAY') THEN DBMS_OUTPUT.PUT_LINE (v_day||', '||v_time);
IF v_time BETWEEN '12:01' AND '24:00' THEN DBMS_OUTPUT.PUT_LINE ('It''s afternoon'); ELSE DBMS_OUTPUT.PUT_LINE ('It''s morning'); END IF;
END IF;
-- control resumes here DBMS_OUTPUT.PUT_LINE ('Done…'); END;
Next, consider the modified version of the script with nested CASE statements. For illustrative purposes, this script uses both CASE and searched CASE statements. All changes are shown in bold letters. SET SERVEROUTPUT ON DECLARE v_day VARCHAR2(15); v_time VARCHAR(8); BEGIN v_day := TO_CHAR(SYSDATE, 'fmDay'); v_time := TO_CHAR(SYSDATE, 'HH24:MI');
-- CASE statement CASE SUBSTR(v_day, 1, 1) WHEN 'S' THEN DBMS_OUTPUT.PUT_LINE (v_day||', '||v_time); -- searched CASE statement CASE WHEN v_time BETWEEN '12:01' AND '24:00' THEN DBMS_OUTPUT.PUT_LINE ('It''s afternoon'); ELSE DBMS_OUTPUT.PUT_LINE ('It''s morning'); END CASE; END CASE;
-- control resumes here DBMS_OUTPUT.PUT_LINE('Done…'); END;
In this exercise, you substitute nested IF statements with nested CASE statements. Consider the outer CASE statement. It uses a selector expression SUBSTR(v_day, 1, 1)
to check if a current day falls on the weekend. Notice that it derives only the first letter of the day. This is a good solution when using a CASE statement because only Saturday and Sunday start with letter 'S'. Furthermore, without using the SUBSTR function, you would need to use a searched CASE statement. You will recall that the value of the WHEN expression is compared to the value of the selector. As a result, the WHEN expression must return a similar datatype. In this example, the selector the expression returns a string datatype, so the WHEN expression must also return a string datatype. Next, you use a searched CASE to validate the time of the day. You will recall that, similar to the IF statement, the WHEN conditions of the searched CASE statement yield Boolean values. When run, this exercise produces the following output: Saturday, 19:49 It's afternoon Done…
PLSQL procedure successfully completed.
|
No comments:
Post a Comment