Oracle PLSQL Programming1
Oracle PLSQL Programming1
Programming
About PL/SQL
DECLARE (Optional)
Variables, Cursors, User-defined exceptions
BEGIN (Mandatory)
- SQL statements
- PL/SQL statements
EXCEPTION (Optional)
Actions to perform when errors occur
END; (Mandatory)
Cont…
Section Description Inclusion
Syntax :
identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr];
Examples :
DECLARE
v_hiredate DATE;
v_deptno NUMBER (2) NOT NULL := 10 ;
v_location VARCHAR2 (13) := ‘NIBM’ ;
c_comm CONSTANT NUMBER := 1400;
Scalar Variable Declarations
• Examples :
DECLARE
v_job VARCHAR2 (9) ;
v_count BINARY_INTEGER := 0 ;
v_total_sal NUMBER (9,2) := 0 ;
v_orderdate DATE := SYSDATE + 7 ;
c_tax_rate CONSTANT NUMBER (3,2) := 8.25;
v_valid BOOLEAN NOT NULL := TRUE;
Cont…
• v_job : Variable to store an employee job title.
• v_count : Variable to count the iterations of a loop
and initialized to 0.
• v_total_sal : Variable to accumulate the total
salary for a department and initialized to 0.
• v_orderdate : Variable to store the ship date of an
order and initialized to one week from today.
• c_tax_rate : A constant variable for the tax rate,
which never changes throughout the PL/SQL
block.
• v_valid : Flag to indicate whether a piece of data
is valid or invalid and initialized to TRUE.
The %TYPE
Attribute
• Declare a variable according to :
- A database column definition
- Another previously declared variable
• Examples:
….
v_name Emp.last_name%TYPE;
v_balance NUMBER (7,2);
v_min_balance v_balance%TYPE :=
…. 10;
Bind Variables
VARIABLE g_salary
NUMBER; BEGIN
SELECT salary
INTO :g_salary
FROM employee
WHERE emp_id = 178;
END;
/
PRINT g_salary;
Referencing Non-PL/SQL Variables
SET SERVEROUTPUT ON
Example :
SET SERVEROUTPUT ON
VARIABL g_monthly_sal
E DEFINE NUMBER; p_annual_sal
= 5000;
DECLARE
v_sal NUMBER (9,2) := &p_annual_sal;
BEGIN
:g_monthly_sal := v_sal / 12;
END;
/
Practice 01
1. Evaluate each of the following declarations.
Determine which of them are not legal and explain
why.
a) DECLARE v_id NUMBER (4);
G_NUM
42
Answer - 02
VARIABLE g_message VARCHAR2 (30);
BEGIN
:g_message := ‘My PL/SQL Block Works’;
END;
/
PRINT g_message;
Alternate Solution
SET SERVEROUTPUT ON
BEGIN
DBMS_OUTPUT.PUT_LINE (‘My PL/SQL Block Works’);
END;
/
Answer – 03
VARIABLE g_char VARCHAR2 (30);
VARIABLE g_num NUMBER;
DECLARE
v_char VARCHAR2 (30);
v_num NUMBER (11,2);
BEGIN
v_char := ‘42 is the answer’;
v_num := TO_NUMBER (SUBSTR
(v_char,1,2));
:g_char := v_char;
:g_num := v_num;
END;
/
PRINT g_char;
PRINT
Answer – 03 (Method 2)
set serveroutput on
--Method 2
DECLARE
v_char VARCHAR2(30);
v_num NUMBER;
BEGIN
v_char := '42 is the Answer';
v_num := TO_NUMBER(substr(v_char,1,2));
DBMS_OUTPUT.PUT_LINE(v_char);
DBMS_OUTPUT.PUT_LINE(v_num);
END;