PLSQL Program Example
PLSQL Program Example
DECLARE
m NUMBER := 7;
n NUMBER := NULL;
o NUMBER := NULL;
p NUMBER := NULL;
q INTEGER := 4;
r INTEGER := 9;
large INTEGER;
----------------------------------
BEGIN
IF m != n THEN -- yields NULL, not TRUE
DBMS_OUTPUT.PUT_LINE('m != n'); -- not run
ELSIF m = n THEN -- also yields NULL
DBMS_OUTPUT.PUT_LINE('m = n');
ELSE
DBMS_OUTPUT.PUT_LINE
('Can not say whether m and n are equal or not.');
END IF;
-----------------------------------
IF o = p THEN -- yields NULL, not TRUE
DBMS_OUTPUT.PUT_LINE('o = p'); -- not run
ELSIF o != p THEN -- yields NULL, not TRUE
DBMS_OUTPUT.PUT_LINE('o != p'); -- not run
ELSE
DBMS_OUTPUT.PUT_LINE('Can not say whether two NULLs are equal');
END IF;
--------------------------------------
IF (q > r) -- If q or r is NULL, then (q > r) is NULL
THEN large := q; -- run if (q > r) is TRUE
ELSE large := r; -- run if (q > r) is FALSE or NULL
DBMS_OUTPUT.PUT_LINE('The value of large : '||large);
END IF;
IF NOT (q > r) -- If q or r is NULL, then NOT (q > r) is NULL
THEN large := r; -- run if NOT (q > r) is TRUE
ELSE large := q; -- run if NOT (q > r) is FALSE or NULL
DBMS_OUTPUT.PUT_LINE('The value of large : '||large);
END IF;
END;
/
Write a PL/SQL block to adjust the salary of the employee whose ID 122.
DECLARE
salary_of_emp NUMBER(8,2);
PROCEDURE approx_salary (
emp NUMBER,
empsal IN OUT NUMBER,
addless NUMBER
) IS
BEGIN
empsal := empsal + addless;
END;
BEGIN
SELECT salary INTO salary_of_emp
FROM employees
WHERE employee_id = 122;
DBMS_OUTPUT.PUT_LINE
('Before invoking procedure, salary_of_emp: ' || salary_of_emp);
DBMS_OUTPUT.PUT_LINE
('After invoking procedure, salary_of_emp: ' || salary_of_emp);
END;
/
Result:
Before invoking procedure, salary_of_emp: 7900
After invoking procedure, salary_of_emp: 8900
Write a PL/SQL block to show single and multiline comments.
DECLARE
some_condition BOOLEAN;
pi NUMBER := 3.1415926; -- the value of pi is 3.1415926
: this is single line comment
radius NUMBER := 10;
area NUMBER;
BEGIN
IF 2 + 2 = 4 THEN
some_condition := TRUE;
/* IF is the simple control flow statement : this is multi line
comment*/
END IF;
area := pi * radius**2;
DBMS_OUTPUT.PUT_LINE('The area of the circle is: ' || area);
END;
/
Explicit Cursors
The developers can have their own user-defined context area to run DML operations. Thus
they can exercise more power over it. The declaration section of the PL/SQL block of code
contains explicit cursors. It is normally built on SELECT operations that fetch multiple rows.
Syntax of explicit cursor:
DECLARE
<<Cursor variable>>
BEGIN
END;
Sample 2. Cursors
The following example uses a cursor to select the five highest paid employees from the emp table.
Input Table
SQL> SELECT ename, empno, sal FROM emp ORDER BY sal DESC;