Chapter 2 Practice
1) This is the example how can you use both bind variables that you declare
BEFORE the block and regular scalar ones that you declare within the block.
You can print bind variables outside the block with the PRINT command.
VARIABLE basic_percent NUMBER
VARIABLE calc NUMBER
SET SERVEROUTPUT ON
DECLARE
today DATE := SYSDATE;
tomorrow today%TYPE;
BEGIN
:basic_percent := 45
:calc := :basic_percent/3;
tomorrow := today +1;
DBMS_OUTPUT.PUT_LINE(' Hello World ');
DBMS_OUTPUT.PUT_LINE('TODAY IS : '|| today);
DBMS_OUTPUT.PUT_LINE('TOMORROW IS : ' || tomorrow);
END;
/
PRINT basic_percent
PRINT calc
Hello World
TODAY IS : 14-SEP-09
TOMORROW IS : 15-SEP-09
PL/SQL procedure successfully completed.
BASIC_PERCENT
45
CALC
15
2) Let’s display the exact date and time of this moment and then the same in 18
hours. The scale for time components should be set to miliseconds.
SET SERVEROUTPUT ON
DECLARE
v_datetime TIMESTAMP(3) := SYSTIMESTAMP;
v_tomorrow v_datetime%TYPE;
BEGIN
v_tomorrow := v_datetime + 18/24;
DBMS_OUTPUT.PUT_LINE('Right now is exactly ' || v_datetime || ' day and time');
DBMS_OUTPUT.PUT_LINE('In 18 hours will be exactly ' || v_tomorrow || ' day and
time');
END;
Right now is exactly 14-SEP-09 09.28.24.939 PM day and time
In 18 hours will be exactly 15-SEP-09 03.28.24.000 PM day and time
PL/SQL procedure successfully completed.
3) Lets’ find out when will be your approximate graduation month, assuming you
need exactly 1 year and 3 months more. Exclude fractions of seconds from the output
and use this Date Format for today Sep 14, 2009
SET SERVEROUTPUT ON
DECLARE
v_grad TIMESTAMP(0) ;
BEGIN
v_grad := TO_TIMESTAMP('Sep 14,2009','Mon dd, yyyy')
+ INTERVAL '1-3' YEAR TO MONTH;
DBMS_OUTPUT.PUT_LINE('My graduation month is ' || v_grad) ;
END;
My graduation month is 14-DEC-10 12.00.00 AM
PL/SQL procedure successfully completed.
4) This example is using regular variable, %TYPE variable and substitute variable
for the column value that will be entered at the run-time.
Lets’ figure out the full name for employee with the Id 145.
SET SERVEROUTPUT ON
SET VERIFY OFF -- this will turn off display of OLD and NEW values
DECLARE
v_fname VARCHAR2(20) ;
v_lname employees.last_name%TYPE ;
v_empid employees.employee_id%TYPE := &employee;
BEGIN
SELECT first_name, last_name INTO v_fname, v_lname
FROM employees
WHERE employee_id = v_empid;
DBMS_OUTPUT.PUT_LINE(q'{Employee's name is }' || v_lname ||
', ' || v_fname);
END;
Enter value for employee: 145
Employee's name is Russell, John
PL/SQL procedure successfully completed.