Presentation is loading. Please wait.

Presentation is loading. Please wait.

SQL Stored Procedures and Functions Presented by: Dr. Samir Tartir

Similar presentations


Presentation on theme: "SQL Stored Procedures and Functions Presented by: Dr. Samir Tartir"— Presentation transcript:

1 SQL Stored Procedures and Functions Presented by: Dr. Samir Tartir
Session - 6 Sequence – 8 SQL Stored Procedures and Functions Presented by: Dr. Samir Tartir

2 Outline PL/SQL Stored Procedures Stored Functions
Running Procedures and Functions

3 Stored Procedures Defined set of actions written using PL/SQL
Two parts Procedure specification Procedure body Procedure parameters can be used to pass values from the caller to the procedure or the other way around. Must specify data type.

4 Parameters Create or replace procedure Increase_salary_find_tax (increase_percent IN NUMBER:=7, sal IN OUT NUMBER, tax OUT NUMBER) AS IN means the procedure can read an incoming value from that parameter when the procedure is called OUT means the procedure can use that parameter to send a value back to what called it increase_percent has a default value of 7

5 Example - 1 CREATE OR REPLACE PROCEDURE hello AS Greetings VARCHAR(20); BEGIN Greetings:= 'Hello World'; DBMS_OUTPUT.PUT_LINE(Greetings); END hello; /

6 Example - 2 CREATE OR REPLACE PROCEDURE increase ( oldprice NUMBER, percent NUMBER := 5, newprice OUT NUMBER) AS BEGIN newprice:=oldprice+oldprice*percent/100; END increase; /

7 Example - 3 CREATE OR REPLACE PROCEDURE NewSal( ESSN NUMBER, Percent NUMBER, NEWSAL OUT NUMBER) AS SAL NUMBER; BEGIN SELECT SALARY+SALARY*Percent/100 INTO NEWSAL FROM EMPLOYEE WHERE SSN = ESSN; END NewSal; /

8 Stored Functions CREATE OR REPLACE FUNCTION discount ( amount NUMBER, percent NUMBER := 5) RETURN NUMBER AS BEGIN IF (amount>=0) THEN return (amount*percent/100); ELSE return(0); END IF; END discount; /

9 Compilation Errors When creating the procedure, if there are errors in its definition, they will not be shown To see the errors of a procedure called myProcedure, type SHOW ERRORS PROCEDURE myProcedure For functions, type SHOW ERRORS FUNCTION myFunction The following statements shows errors of the last compiled code SHOW ERROR (or SHO ERR for short)

10 Running a Procedure or Function
set serveroutput on EXEC hello; declare out number; begin increase(10,5,out); DBMS_OUTPUT.PUT_LINE(out); end; / declare out number; begin NewSal( ,10,out); DBMS_OUTPUT.PUT_LINE(out); end; / out := discount(100,5);

11 SUMMARY Oracle uses PL/SQL to include business logic right in the database directly. DBMS’s use stored procedures and stored functions to call server-side from middle-tear programs

12 Resources & References
Dr. Samir Tartir Website: Fundamentals of Database Systems by El Masri & Navathe. Publisher : Addison-Wesley, 5th edition, 2006.


Download ppt "SQL Stored Procedures and Functions Presented by: Dr. Samir Tartir"

Similar presentations


Ads by Google