PL SQL Basics
PL SQL Basics
Objectives
• At the end of this session, you will be able to:
4
Need for PL/SQL (Contd.)
• PL/SQL improves the performance when multiple
SQL statements are to be executed.
– Without PL/SQL, Oracle must process SQL statements
one at a time.
– Programs that issue many SQL statements require
multiple calls to the database, resulting in significant
network and performance overhead.
– With PL/SQL, an entire block of statements can be
sent to Oracle at one time. This can drastically reduce
network traffic between the database and an
application.
CONFIDENTIAL© Copyright 2008 Tech
5
Mahindra Limited
PL/SQL Improves Performance
DECLARE
Variables, cursors, user-defined
exceptions, etc.
BEGIN
EXCEPTION
END;
• Initialize identifiers by using the assignment operator (:=) or the reserved word
“DEFAULT”
• Use DBMS_OUTPUT.PUT_LINE.
X NUMBER(3) := 10;
Y NUMBER(3) := 20;
BEGIN
END;
BEGIN
SELECT (sal*12)+nvl(comm,0) INTO :result FROM emp WHERE
empno=7839;
DBMS_OUTPUT.PUT_LINE('The total amount payable :
'|| :result);
END;
/
-- To see the value set for the variable on SQL prompt use the
SQL * plus command PRINT
PRINT result
• INSERT
DECLARE
v_empno emp.empno%TYPE := &empno;
v_ename emp.ename%TYPE := ‘&ename’;
v_salary emp.sal%TYPE := &sal;
BEGIN
INSERT INTO emp(empno,ename,sal)
VALUES(v_empno,v_ename,v_salary);
COMMIT;
END;
DECLARE
v_empno emp.empno%TYPE;
v_salary emp.sal%TYPE :=&sal;
BEGIN
UPDATE emp SET sal=v_salary where empno=1234;
COMMIT;
END;
DECLARE
v_empno emp.empno%TYPE :=&eno;
BEGIN
DELETE emp WHERE empno=v_empno;
COMMIT;
END;
DECLARE
v_empno emp.empno%TYPE;
BEGIN
-- Using a sequence to autogenerate the primary key
column values
INSERT INTO emp (empno, ename)
VALUES(seq_emp.NEXTVAL,‘Ajay')
RETURNING empno INTO v_empno;
/* Displaying the value of the sequence that is
inserted in the table */
DBMS_OUTPUT.PUT_LINE(v_empno);
END;
BEGIN
SELECT ename, sal INTO vname, vsal FROM emp WHERE empno = veno;
–- Displays an appropriate message if salary is greater
than 1500
IF vsal > 1500 THEN
DBMS_OUTPUT.PUT_LINE (vname|| ' earns a salary greater
than 1500');
--Else it shows the employee name whose sal is <1500
ELSE
DBMS_OUTPUT.PUT_LINE (vname|| ' earns a salary not greater
than 1500');
END IF;
DBMS_OUTPUT.PUT_LINE ('This line executes irrespective of the
condition');
END;
• WHILE Loops
WHILE condition
LOOP
Statements;
END LOOP;
Condition is evaluated before each
iteration of the loop
DECLARE
v_i NUMBER(2) := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE(‘Value : ‘|| v_i);
EXIT WHEN v_i = 10;
v_i:=v_i+1;
END LOOP;
END;
DECLARE
v_i NUMBER(2) := 1;
BEGIN
WHILE ( v_i <= 10 )
LOOP
DBMS_OUTPUT.PUT_LINE(‘Value : ‘|| v_i);
v_i:=v_i+1;
END LOOP;
END;
BEGIN
FOR v_i IN 1..10
/* The LOOP VARIABLE v_i of type BINARY_INTEGER
is declared automatically */
LOOP
DBMS_OUTPUT.PUT_LINE(‘Value : ‘|| v_i);
END LOOP;
END;