Presentation is loading. Please wait.

Presentation is loading. Please wait.

PL/SQL – Session 1 of 4 Instructor: Jim Cody

Similar presentations


Presentation on theme: "PL/SQL – Session 1 of 4 Instructor: Jim Cody"— Presentation transcript:

1 PL/SQL – Session 1 of 4 Instructor: Jim Cody

2 Overview

3 Course Topics What is PL/SQL? Creating & Running PL/SQL Code
PL/SQL Fundamentals Working with Functions Conditional Statements Iterative Processing Exception Handling Working with Procedures

4 Session 1 SQL Refresher What is PL/SQL Connecting to the Database
The Big Picture – Functions & Procedures

5 SQL Refresher See emailed files.
There are also many tutorials (free) on the web.

6 What is PL/SQL

7 What is PL/SQL? Procedural Language (PL) extension to the Structured Query Language (SQL) Introduced by ORACLE to overcome some of the limitations of SQL and to provide a more complete programming language. PL/SQL is: Highly structured and readable Standardized and portable across ORACLE products An embedded language

8 Functions and Procedures
Functions and Procedures are pre-defined pieces of code that perform database work (like a view). Functions run select statements and return a single* value. Procedures are typically used to perform and action - insert, update and delete statements. They do not return data. Functions can be run from a select statement. Procedures cannot. * Functions can be modified to return multiple values but then cannot be used in a select statement which is how they provide their value.

9 PL/SQL – A Definition Declaration Section Variables and Cursors
Create or Replace Procedure name AS A PL/SQL function or procedure contains three sections: Declaration, Executable, and Exception. In PL/SQL you can develop logic that can be executed in: SQL*Plus A Stored Procedure A Stored Function Database Trigger Package Declaration Section Variables and Cursors Executable Section Procedural & SQL statements PL/SQL is a proprietary language from Oracle. It allows database developers to add language statements, similar to C language statements, to traditional SQL statements in a script. PL/SQL offers constructs such as variable declarations, IF-Then-Else statements, and Loop statements. The PL/SQL language is used in Oracle to build several types of application constructs. These application constructs include: SQL*Plus script: SQL*Plus script can include PL/SQL subprograms. Therefore, much more powerful SQL scripts, that include PL/SQL logic, could be saved as files. These files could then be “started” in SQL*Plus. Stored Procedures or Functions: A stored procedure or function is a PL/SQL subprogram that can be invoked by a client application, database trigger, or an Oracle tool application trigger. This technique, in some cases, is superior to the shipping of ODBC based SQL strings through the network for execution by the Oracle server. Stored Procedures reside on the Database Server and therefore will run faster than ODBC requests. In addition, since many clients share the same Stored Procedure, a logic change to a Stored Procedure would be immediately felt in all client applications. Database Trigger A database trigger is a PL/SQL subprogram that performs some action based on the execution of an Insert, Update or Delete request against a database table. Business rules are often implemented in database triggers. Database triggers could also be used to enforce security, perform complex validation of column values, change a column based on the value of another column, and document changes to a record by writing a log record to another table. Application Trigger Oracle application tools such as forms and reports are equipped with a PL/SQL engine so that developers can construct application triggers using PL/SQL. Package A package is a set of PL/SQL procedures, functions, cursors, and other PL/SQL variables that have been bundled together into a complete package. Exception Section Error handling statements End;

10 Connecting to the Database

11 Setting Up SQL Developer

12 Setting Up SQL Developer

13 Setting Up SQL Developer
Password: 1K.bE0bpj Fill in the appropriate values Press ‘TEST’ If Status = ‘Success’, press ‘SAVE’ Press ‘CANCEL’ to close the window

14 Setting Up SQL Developer
Double-click (or right mouse button… Connect) to connect to the class database

15 Class Database Tables

16 Basic Syntax

17 Blocks Anonymous – block sections are not named. Limited and narrow usage. Named – creates a stored piece of code with a name. Create or replace function xyx…. Create or replace procedure abc…. Named blocks can be nested in other blocks.

18 Basic Anonymous Block Begin; End; / Two important notes:
You must have a statement in each block. Forward slash executes the code as PL/SQL. Begin Null; This will not work!! begin dbms_output.put_line('hey'); end; /

19 Anonymous Block with Display
Set serveroutput on size ; begin dbms_output.put_line(‘Hello World'); end; /

20 PL/SQL Functions – A Definition
A Function can return a value to the caller. The value is returned to the caller through the use of a RETURN keyword within the function. Functions can be referenced directly in SQL Queries. Create Function Syntax: create [or replace] function functionname [ (argument IN | OUT | IN OUT datatype) ] … return datatype is argument datatype; begin return (argument); exception end; Note: Every Function must have a return clause.

21 PL/SQL Function Example
select orders.order_num, sum(quantity*2.3) as cost from orders, orderitems where orders.order_num = orderitems.order_num group by orders.order_num order by order_num We want to run something simple: select order_num, qty_cost(order_num) as cost from orders; Imagine this is much more complicated. This is the name of the function. This is the value passed to the function.

22 PL/SQL Function Example
Create or Replace Function qty_cost (in_ordernum IN Integer) return Integer is line_cost integer; Begin SELECT sum(quantity * 2.3) as lcost into line_cost FROM orderitems WHERE order_num = in_ordernum group by order_num; return line_cost; end; / To test: select order_num, qty_cost(order_num) as cost from orders;

23 PL/SQL Procedures – A Definition
The syntax for the Create Procedure command is as follows: Create Procedure Syntax: create [or replace] procedure procedurename [ (argument IN | OUT | IN OUT datatype) ] … as variable datatype; begin exception end;

24 PL/SQL Procedure Example
Create or Replace Procedure AddMfg (in_vendorid IN Integer, in_name IN String) as my_address vendors.vend_address%Type; begin My_Address := 'Unknown'; Insert into Manufacturer(mfg_id, mfg_name, mfg_address) values (in_vendorid, in_name, my_address); end; / To Use it: execute AddMfg(2,'new vendor'); To Check it: select * from manufacturer;

25 Future Topics

26 PL/SQL – Handling Exceptions
Predefined Exceptions: DUP_VAL_ON_INDEX Duplicate value for index column. INVALID_NUMBER SQL statement specifies an invalid number.   NO_DATA_FOUND Select statement doesn’t return any rows. TOO_MANY_ROWS A Select statement has retrieved more than 1 row. VALUE_ERROR Truncation or conversion error. User-Defined Exceptions: Salary_Too_Low exception; MySalary NUMBER(10,2); begin Select Salary from Person Into MySalary Where person = in_person; If MySalary < then RAISE Salary_Too_Low; End If; return (‘Salary OK’);   exception When Salary_Too_Low then return (‘Salary too low’); end;

27 PL/SQL – If /Then / Else Syntax
IF condition THEN statement; … statement; [ELSIF condition THEN statement; … statement;] [ELSE END IF; Example: IF My_price < 5000 THEN My_price := My_price * 1; ELSE My_price := My_price * 0.75; Note: The ELSIF and ELSE clauses are optional. An IF statement can have multiple ELSIF clauses but only one ELSE clause. ELSIF is valid. ELSEIF is invalid.

28 PL/SQL – While / Loop Syntax
WHILE condition LOOP statement; … statement; END LOOP; Example: create or replace procedure WhileLoopSample as MyUser_ID Positive := 1; MyUser_Nm VarChar2(30); begin WHILE MyUser_ID < 101 LOOP MyUser_Nm := ‘Temp’ || MyUser_ID; insert into Users (UserID, UserName, RoleID, Password) values (MyUser_ID, MyUser_Nm,5,'ChangeMe'); MyUser_ID := MyUserID + 1; end;

29 PL/SQL – Cursor Processing
A Cursor is used to process multiple rows retrieved from the database. Using a cursor, your program can step through the set of returned rows one at a time, processing each row in turn. BASE TABLE RecordSet CURSOR SQL Statement BASE TABLE Cursor Functions: DECLARE the recordset OPEN the recordset FETCH a row and move through the recordset CLOSE the recordset

30 PL/SQL – SQL Syntax (Update)
Java Program public void ServiceOrderAccept(int serviceorderid) throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException { String mySQL = "{call ServiceOrderAccept(?)}"; myDB.createConnection(); csmt = myDB.conn.prepareCall(mySQL); csmt.setInt(1, serviceorderid); csmt.executeQuery(); myDB.closeConnection(); } The form of an UPDATE statement is as follows: Update table-reference SET column-name = expression, … WHERE where-clause; Database Procedure Create or Replace Procedure ServiceOrderAccept (in_serviceOrderID IN Integer) as begin Update ServiceOrder Set SoStatusID = 10 where serviceOrderID = in_serviceOrderID; Commit; end;

31 PL/SQL – Operators & Delimiters
+ Addition Operator - Subtraction Operator * Multiplication Operator / Division Operator = Equality Operator < Less than Operator > Greater than Operator ; Statement terminator ' Character String Delimiter " Quoted String Delimiter <> Not Equal To Operator != Same as <> <= Less Than Or Equal To Operator >= Greater Than or Equal To Operator := Assignment Operator || Concatenation Operator -- Single Line Comment /* */ Multiple Line Comments << >> Label Delimiters <space> Space <tab> Tab <cr> Carriage return Examples: MyUser_Nm := 'Temp' || MyUser_ID; My_Address := 'Unknown'; My_discount := My_discount * 0.75; If MySalary < then RAISE Salary_Too_Low; End If;

32 PL/SQL – Standard ORACLE Datatypes
….. AS Lv_number NUMBER(6,2); Lv_number NUMBER(15,2) := ; Lv_number INTEGER; Lv_character1 VARCHAR2(40); Lv_date1 DATE := ’28-Jun-12’; Lv_date2 DATE := ’28-Jun-2012’; Lv_date3 DATE := to_date(‘ ’,’YYYYMMDD’); Lv_date4 DATE := SYSDATE; Lv_date5 TIMESTAMP := SYSTIMESTAMP;

33 PL/SQL – Datatypes Example:
In addition to the normal Oracle SQL datatypes, PL/SQL allows you to declare variables with these datatypes. The maximum length of a variable name is 30 characters. Boolean Can be assigned the constants True or False. Binary_Integer Integers in the range –2,147,483,647 to 2,147,483,647. Natural Integers from 0 to 2,147,483,647. Positive Integers from 1 to 2,147,483,647. %Type A Table.Column’s datatype. You must declare all variables and constants that are referenced in the PL/SQL statements. SQL Cursors must also be declared. Example: Create or Replace Procedure AddDistributor (in_distributorid IN Integer, in_name IN String) as my_address Distributor.Address1%Type; begin My_Address := 'Unknown'; Insert into Distributor(DistributorID, DistributorName, Address1) values (in_distributorid, in_name, my_address); end; /

34 Test Procedures Create or Replace Procedure UpdateAddress (in_distributorid In Integer, in_street IN VarChar2, in_city IN VarChar2, in_statecode IN VarChar2, in_zip IN VarChar2, in_phone IN VarChar2, in_fax IN VarChar2) as begin Update Distributor Set address1 = in_street, city = in_city, provinceabbreviation = in_statecode, postalcode = in_zip, phone = in_phone, fax = in_fax Where distributorid = in_distributorid; Commit; end;

35 Show Errors Show Errors provides much more detail for debugging.


Download ppt "PL/SQL – Session 1 of 4 Instructor: Jim Cody"

Similar presentations


Ads by Google