* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download ORACLE: PL/SQL What is PL/SQL
Survey
Document related concepts
Tandem Computers wikipedia , lookup
Microsoft Access wikipedia , lookup
Functional Database Model wikipedia , lookup
Entity–attribute–value model wikipedia , lookup
Ingres (database) wikipedia , lookup
Extensible Storage Engine wikipedia , lookup
Microsoft Jet Database Engine wikipedia , lookup
Oracle Database wikipedia , lookup
Clusterpoint wikipedia , lookup
Database model wikipedia , lookup
Open Database Connectivity wikipedia , lookup
Relational model wikipedia , lookup
Transcript
An Introduction to Oracle Victor Matos 1 What is ORACLE ? • Very robust implementation of a Relational Database Management System (RDBMS) The relational model of data is simple to understand and has been extensively scrutinized since 1970’s 2 What else is good about ORACLE ? • The company is solid and successful, since 1994 revenues in the order of $2+ billion/year • Very popular software, worldwide distribution • Runs in 100+ different type of computers 3 Reasons for the Oracle Success • Security Mechanisms users are given specific rights to operate on the data. • Backup and Recovery minimizes data loss and idle time in the presence of failures • Space Management flexible allocation • Open Connectivity uninterrupted services reachable from heterogeneous clients • Development Tools many to choose from 4 Parts of the Oracle Server • Procedural Option: built-in programming capabilities based on the PL/SQL language • Stored Procedures: programs stored in the server-side could be invoked using an ADAlike interface • Triggers: dormant server-side routines which are ‘fired’ when specific maintenance conditions are met 5 Parts of the Oracle Server cont • Packages: libraries of server-side routines including proc, functions, triggers, user defined data types, constants, variables. ORACLE PACKAGES Various Clients ORACLE SERV ER Same set of Proc, functions, datatype, const, etc 6 Parts of the Oracle Server cont • Distributed Option: data could be stored in different machines and placed in different cities. Oracle Distributed option provides location transparency, the user does not need to be aware of where the data is kept. 7 Oracle Distributed Option Cleveland, Ohio Ohio Inventory Workstation SELECT PartNumber, Price FROM Ohio_inventory, suppliers WHERE inv_sup = Sup_Numb; Indians95 Oraccle Server NETWORK New York, NY. Suppliers Yankees96 ORACLE Server 8 Parts of the Oracle Server cont • Parallel Server Option: Independent machines (nodes) which their own memory and disk space could tap into a common disk database. This loosely coupled architecture provides data sharing and message exchange between processes 9 Parallel Server Option NODE 1 Cleveland, Ohio NODE 2 New York, NY. NY data Ohio data Shared Database Indians95 Oraccle Server Yankees96 ORACLE Server 10 Parts of the Oracle Server cont • Parallel Query Option: Computers holding more than one CPU (such as multiPentium Windows NT) could use those processors in solving independent portions of a query. An Oracle control unit breaks the query into pieces, and re-assembles the partial results. 11 Parallel Query Option Cleveland, Ohio Original SQL statement SELECT LastName, Dno FROM Employee WHERE (salary > 70000) or (sex = 'F') Ohio data Pentium 1 SELECT LastName, Dno FROM Employee WHERE (salary > 70000) Indians95 Oraccle Server Dual Pentium Window s NT4.0 Pentium 2 OR SELECT LastName, Dno FROM Employee WHERE (sex = 'F') Results 12 ORACLE Products SQL * Plus: User-Friendly-Interface, superset of SQL Oracle-Forms GUI interface (forms, menu, libraries) Oracle-Reports Multimedia reporting (text, images, charts) Oracle Loader Migration facilitator, legacy data to Oracle Developer 2000 Integrated development environment: Designer 2000 Forms, Reports, Graphics, Book, Browser, Procedure builder, SQL*Plus, CASE Personal Oracle Full version of the Oracle server for the PC 13 ORACLE Architecture Terminology An instance is a portion of the computers memory and a collection of processes required by Oracle to operate A database is the name of a reserved disk area A tablespace is a collection of datafiles (or tables) A table is a ‘file’ or container for application-specific data 14 ORACLE Architecture Terminology: Rollback is the action of setting a data item to its previous value. For instance, assume an account holds $50, if a deposit of $1000 on this account is not completed the balance is set back to $50. Undo is similar to roll-back, the action of resetting a data item to its most recent previous value Dirty-block is a memory resident image of a disk block which has been changed by a process while in memory LRU flushes from memory the block which for the longest 15 period of time has not been used ORACLE Architecture Physical Structure Definition Datafiles Contain all of the database data; logical structures , such as tables and indexes Hold records of all changes made to the database for recovery purposes Record the physical structure and status of the database Contain startup values for database parameters (often referred as the init.ora file ) Redo Log Files Control Files Parameter File 16 ORACLE Architecture A. What is inside of the database dictionary? SQL> column comments format a35 wrap SQL> select * from dictionary; TABLE_NAME COMMENTS ------------------------------ -----------------------------ALL_CATALOG All tables, views, synonyms, and sequences accessible to the user ALL_CLUSTERS Description of clusters accessible to the user ALL_CONSTRAINTS Constraint definitions on acce ssible tables … 276 rows selected. … 17 ORACLE Architecture B. What is inside of a datafile? SQL> describe Name ----------NAME TYPE LINE TEXT user_source Null? -------NOT NULL NOT NULL Type -------VARCHAR2(30) VARCHAR2(12) NUMBER VARCHAR2(2000) NOTE: You could use desc instead of describe 18 ORACLE Architecture How to create objects in ORACLE Objects in an ORACLE database are created in the following order 1. create database 2. create tablespace(s) 3. create rollback segment (s) 4. create user(s) 5. create table(s) 6. create index 7. create other objects such as: sequence, cluster, procedure, function, package, trigger, link, profile, synonym, schema, snapshot, view, etc. 19 ORACLE Architecture 1. CREATE DATABASE Command Used to create a database, making it available for general use, with the following options: o to establish a maximum number of instances, data files, o redo log files groups, or redo log file members o to specify names and sizes of data files and redo log files o to choose a mode of use for the redo log Warning: This command prepares a database for initial use and erases any data currently in the specified files. Only use this command when you understand its ramifications. 20 ORACLE Architecture CREATE DATABASE Command create database Oracle controlfile reuse logfile 'D:\ORAWIN95\DATABASE\log1orcl.ora' size 200K reuse, 'D:\ORAWIN95\DATABASE\log2orcl.ora' size 200K reuse datafile 'D:\ORAWIN95\DATABASE\sys1orcl.ora' size 20M reuse autoextend on next 10M maxsize 200M character set WE8ISO8859P1; 21 ORACLE Architecture CREATE DATABASE Command (details) CONTROLFILE REUSE reuses existing control files identified by the initialization parameter CONTROL_FILES LOGFILE specifies one or more files to be used as redo log files. MAXLOGFILES specifies the maximum number of redo log file groups that can ever be created for the database. MAXLOGMEMBERS specifies the max number of copies, for a redo log file group. MAXLOGHISTORY specifies the max number of archived redo log files for automatic media recovery of Oracle7 with the Parallel Server option. MAXINSTANCES specifies the max number of instances that can simultaneously have this database mounted and open. 22 ORACLE Architecture CREATE DATABASE Command (details) ARCHIVELOG In this mode, the contents of a redo log file group must be archived before the group can be reused. NOARCHIVELOG In this mode, the contents of a redo log file group need not be archived before the group can be reused. CHARACTER SET specifies the character set the database uses to store data. DATAFILE specifies one or more files to be used as data files. These files all become part of the SYSTEM tablespace. AUTOEXTEND enables or disables the automatic extension of a datafile. 23 ORACLE Architecture How to create a TableSpace CREATE TABLESPACE MyTabspace_2 DATAFILE 'd:\ORAWIN95\DATABASE\MyData2.dat' SIZE 10M DEFAULT STORAGE ( INITIAL 10K NEXT 50K MINEXTENTS 1 MAXEXTENTS 999 PCTINCREASE 10) ONLINE; How to eliminate a tablespace DROP TABLESPACE Mytabspace2 INCLUDING CONTENTS CASCADE CONSTRAINTS; 24 ORACLE Architecture Create additional tablespaces -- USER_DATA: “Create user” command sets this as the default tablespace -- TEMPORARY_DATA: Create user sets this as the temporary tablespace -- ROLLBACK_DATA: For rollback segments create tablespace user_data datafile 'D:\ORAWIN95\DATABASE\usr1orcl.ora' size 3M reuse autoextend on next 5M maxsize 150M; create tablespace rollback_data datafile 'D:\ORAWIN95\DATABASE\rbs1orcl.ora' size 5M reuse autoextend on next 5M maxsize 150M; create tablespace temporary_data datafile 'D:\ORAWIN95\DATABASE\tmp1orcl.ora' size 2M reuse autoextend on next 5M maxsize 150M; 25 ORACLE Architecture Rollback_data rbs1orcl User_data usr1orcl usr2orcl 26 ORACLE Architecture 3. Create Rollback Segment A rollback segment is an object that Oracle7 uses to store data necessary to reverse, or undo, changes made by transactions. Example The following statement creates a rollback segment (rbs_temp) with default storage values in the system tablespace: CREATE ROLLBACK SEGMENT rbs_temp TABLESPACE system; 27 ORACLE Architecture Creating Rollback Segments -- Create 16 rollback segments. Allows 16 concurrent users with open -- transactions updating the database. This should be enough???. create public rollback segment rb1 storage(initial 50K next 50K) tablespace rollback_data; create public rollback segment rb2 storage(initial 50K next 50K) tablespace rollback_data; … create public rollback segment rb16 storage(initial 50K next 50K) tablespace rollback_data; 28 ORACLE Architecture Asking for the datafiles, and tablespaces in the current database SQL> select file_name, tablespace_name, bytes from dba_data_files; FILE_NAME TABLESPACE_NAME BYTES ------------------------------ ------------------------------ --------D:\ORA95\DATABASE\usr1orcl.ora USER_DATA 3145728 D:\ORA95\DATABASE\rbs1orcl.ora ROLLBACK_DATA 5242880 D:\ORA95\DATABASE\tmp1orcl.ora TEMPORARY_DATA 2097152 D:\ORA95\DATABASE\sys1orcl.ora SYSTEM 10485760 d:\ORA95\DATABASE\MyData2.dat MYTABSPACE_2 10485760 DATABASE USER DATA Rollback_ T emporary Data _ Data System Oracle MYTABSPACE_2 Tablespaces 29 (under construction!) Architecture Summary: 1- tablespace 2- redo log 3- control files 4- user proc 5- server proc (dbwrt, ckpt, lgwr, smon, pmon, arch, lckn, reco) 6- sga (dict, datacache, redolog, sqlarea) 7- instances 30 SQL * Plus SQL*Plus is a user-friendly-interface imitating a notepad. Its primary use is in supporting the construction of simple schema objects. o Normally used to easily interact with the Oracle server o Facilitates the prototyping of SQL commands o ”Quick and dirty” way of developing/testing PL-SQL and other Oracle objects 31 Using SQL * Plus to create Objects Schema Objects • users • • • • • • • tables views sequences synonyms indexes clusters hash clusters Other schema objects such as packages, and triggers will be discussed later. 32 Using SQL * Plus to create Objects Create User Command Creates a database user, or an account through which you can log in to the database. You can optionally assign the following properties to the user: •default tablespace •temporary tablespace •quotas for allocating space in tablespaces •profile containing resource limits Example: You can create the user MARIA by issuing the following statement: CREATE USER Maria IDENTIFIED BY Macarena DEFAULT TABLESPACE payroll_ts QUOTA 10M ON payroll_ts QUOTA 5M ON temp_ts QUOTA 5M ON system PROFILE accountant; Grant Connect, Resource to Maria; 33 Using SQL * Plus to create Objects Schema Objects: TABLES • Tables are the basic unit of data storage in an Oracle database. • Data is stored in rows and columns. • Typical datatypes are: CHAR, VARCHAR2, NUMBER, DATE • A row is a collection of column information corresponding to a single record. • You can optionally specify rules for each column of a table. These rules are called integrity constraints. Example: NOT NULL • Once you create a table, you insert rows of data using SQL statements. • Table data can then be queried, deleted, or updated using SQL. 34 Using SQL * Plus to create Objects Create Table Command Example I. To define the EMP table owned by SCOTT, you could issue the following statement: CREATE TABLE scott.emp ( empno NUMBER CONSTRAINT pk_emp PRIMARY KEY, ename VARCHAR2(10) CONSTRAINT nn_ename NOT NULL CONSTRAINT upper_ename CHECK (ename = UPPER(ename)), job VARCHAR2(9), mgr NUMBER CONSTRAINT fk_mgr REFERENCES scott.emp(empno), hiredate DATE DEFAULT SYSDATE, sal NUMBER(10,2) CONSTRAINT ck_sal CHECK (sal > 500), comm NUMBER(9,0) DEFAULT NULL, deptno NUMBER(2) CONSTRAINT nn_deptno NOT NULL CONSTRAINT fk_deptno REFERENCES scott.dept(deptno) ) PCTFREE 5 PCTUSED 75 ; 35 Using SQL * Plus to create Objects Create Table Command Notes 1- This table contains 8 columns. Ex: EMPNO column is of datatype NUMBER and has an associated integrity constraint named PK_EMP. 2- HIRDEDATE column is of datatype DATE and has a default value of SYSDATE. 3- PCTFREE of 5 indicates that 5% of space is reserved for future updates 4- PCTUSED of 75, says that a minimum of 75% of the table should be used on each data block 5- The constraint on the mgr field indicates that such a value (mgr’s id) must also be found in the scott.emp table (a recursive reference) 36 Using SQL * Plus to create Objects Create Table Command. Typical data types Data Type Use CHAR Alpha-numeric, Fixed data length Alphanumeric, variable-length Numeric data: Integers an float Date data such as: ‘01-APR-97’ VARCHAR2 NUMBER DATE 37 Using SQL * Plus to create Objects Create Table Command. Example II. Assuming you have the parallel query option, then the fastest method to create a table that has the same columns as the EMP table, but only for those employees in department 10, is to issue a command similar to the following: CREATE TABLE emp_tmp UNRECOVERABLE PARALLEL (DEGREE 3) AS SELECT * FROM emp WHERE deptno = 10; Notes 1- The UNRECOVERABLE keyword speeds up table creation because there is no overhead in generating and logging redo information. 2- Parallelism speeds up the creation of the table. 3- After the table is created, querying the table is also faster because the same degree of 38 parallelism is used to access the table. ORACLE: PL/SQL What is PL/SQL ? • PL/SQL stands for Procedural extensions to SQL. It adds programming capabilities to SQL. •It is a block-structured language with a syntax similar to C • Normally used on the server-side, however some client-side products (ORA-FORMS) could also have it as a built-in part. • It is not a stand-alone language 39 PL/SQL Architecture CLIENT SIDE CODE VisualBasic Java C, C++ COBOL MS-Access PowerSoft People’s Soft SAP HTML + scripts (JavaScript, Perl, VBS) ORACLE SERVER CODE PL-SQL (Oracle 7, 8, 8i) Java (Oracle8i) ... 40 PL/SQL Architecture Client side Third-Party Products Call tp Stored Procedures ORACLE Forms Local PL/SQL Program SQL Generator SQL Statement SQL Statement ORACLE Server SQL Statements Processor PL/SQL Runtime Engine Call to Stored Proc Call to Stored Proc Stored Program Unit PL/SQL V2.x Runtime Engine 41 PL/SQL Programming • PL/SQL = SQL + standard procedural programming • Support for procedures, functions, flow-control statements, declared variables, user-defined types. • A PL/SQL program is either a procedure, a function, or an anonymous block • Anonymous blocks are nameless fragments of code normally executed as script files 42 PL/SQL Programming Block-Structure Declaration Section Execution Section Exception Section 43 PL/SQL: Example1 -- CELCIUS1 (Lowest temp, Highest Temp) Converts Fahrenheit temperatures to Celcius. Results are saved -- into TEMP, a table predefined to hold (number, number, text) CREATE OR REPLACE PROCEDURE Celcius1 (Low IN NUMBER, High IN NUMBER) IS Celcius number; Fahren number; Msg varchar2(55); BEGIN DELETE FROM temp; FOR Fahren IN Low..High LOOP Celcius:= ROUND ( (Fahren -32)*5/9 ); IF (Fahren < 30 ) THEN Msg := 'Too cold'; ELSIF (Fahren < 70 ) THEN Msg := 'Cold'; ELSIF (Fahren <80) THEN Msg := 'Very nice'; Create table Temp (…) ELSE Msg := 'Hot'; END IF; INSERT INTO Temp VALUES (Fahren, Celcius, Msg); END LOOP; END; 44 PL/SQL: Example1 Test the program using the following SQL*PLUS commands SQL> delete from Temp; SQL> execute Celcius1(0,100); SQL> select * from temp; F1 F2 F3 --------------- ---------- -----------…… ... 68 20 Cold 69 21 Cold 70 21 Very nice 71 22 Very nice 72 22 Very nice 73 23 Very nice 74 23 Very nice 75 24 Very nice 76 24 Very nice 77 25 Very nice 78 26 Very nice 79 26 Very nice 80 27 Hot 81 27 Hot 45 PL/SQL: Example1 A second way of testing a stored procedures is to call it from an anonymous block. Type in the following code sql> edit CelciusTest DECLARE BEGIN delete from Temp; Celcius1 (0,100); END; sql> @celciusTest sql> / sql > select * from Temp; 46 PL/SQL: Example2 The COMPANY database 47 PL/SQL: Example2 -- WorkLoad -- Employees are either assigned/removed to/from a project CREATE or REPLACE PROCEDURE WorkLoad ( p_action VARCHAR2, p_ssn VARCHAR2, p_pno NUMBER, p_hours NUMBER:= 40 ) IS BEGIN IF (p_action = 'ASSIGN' ) THEN INSERT INTO works_on VALUES (p_ssn, p_pno, p_hours); ELSIF (p_action = 'REMOVE') THEN DELETE FROM works_on WHERE (essn = p_ssn) AND (pno = p_pno); END IF; END; 48 PL/SQL: Example2 Testing the procedure with an anonymous block. SQL > edit workLoadTest DECLARE BEGIN WorkLoad('ASSIGN',123456789,10,1.7); END; sql> @workLoadTest sql> / sql> select * from Works_On; 49 PL/SQL Programming PL/SQL Syntax Assignment x := x + 1; Condition Testing if (condition) then [elsif (condition) then] [else] end if; for i in -1..10 Loop ... end loop; while (cond) Loop ... end loop; Loop ... end loop < ,<>, >, <= , >= , = and, or, not Loops Conditions 50 PL/SQL Programming Defining/Initializing Variables Salary DeptNumber LastName Sex JobType TaxDate NUMBER(10,2); NUMBER := 17; VARCHAR2(20); CHAR := ‘F’; CHAR(15); DATE := ‘15-APR-99’; Most common data types are: NUMBER, VARCHAR2, DATE 51 PL/SQL Programming Defining Variables %TYPE Declares a variable with respect to a Table.Column Bonus EMP.Sal%TYPE; EMP EMPNO ----7369 7499 7521 ENAME ---------SMITH ALLEN WARD JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 Number(7,2) 52 PL/SQL Programming Defining Variables %ROWTYPE Defines a record with respect to an existing table definition TempEmp EMP%ROWTYPE; Refers to fields using: TempEmp.Salary EMP EMPNO ----7369 7499 7521 ENAME ---------SMITH ALLEN WARD JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------CLERK 7902 17-DEC-80 800 20 SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 53 PL/SQL Programming Creating/Debugging a Stored PL/SQL Function This example shows how to create an debug a PL/SQL stored function using SQL*Plus CREATE or REPLACE FUNCTION IsFile ( MyTable IN VARCHAR2 ) RETURN ( boolean ) IS result user_tables.table_name%TYPE; BEGIN Intentional SELECT table_name INTO result error FROM user_tables WHERE table_name = UPPER(MyTable); RETURN true; EXCEPTION WHEN No_Data_Found THEN RETURN false; END; / 54 PL/SQL Programming Creating/Debugging a Stored PL/SQL Function SQL> @isfile Warning: Function created with compilation errors. SQL> show errors Errors for FUNCTION ISFILE: Line and column where error was found LINE/COL ERROR -------- -------------------------------------------------1/47 PLS-00103: Encountered the symbol "(" when expecting one of the following:<an identifier> <a double-quoted delimited-identifier> LONG_ double SQL> EDIT IsFile.sql Use the editor to correct each error in the script file 55 PL/SQL Programming Creating/Debugging a Stored PL/SQL Function -- Testing ISFILE( ) function, using an anonymous block -- Script: isFileTest. Author: V.Matos May 22, 1999. clear screen DECLARE -- put file names here theFile user_tables.table_name%TYPE := 'EMPXYZ'; BEGIN delete from temp; if ISFILE(theFile) then insert into temp values (1,1, theFile || ' exists'); else insert into temp values (2,2, theFile || ' does NOT exist'); end if; END; / select * from TEMP; clear buffer -- erase this line and try again / 56 PL/SQL Programming Testing the Anonymous Procedure Running the anonymous script SQL> @isFileTest procedure successfully executed SQL> select * from TEMP; F1 F2 F3 ---- ---- ---------------------2 2 EMPXYZ does NOT exist Results are placed into the TEMP table 57 PL/SQL Programming -- RaiseSalary: Function increases salary of certain employee by PctRaise CREATE or REPLACE FUNCTION RaiseSalary ( EmpSsn number, PctRaise number ) RETURN number IS Default type is ‘IN’ NewSalary number; OldSalary number; BEGIN SELECT Salary INTO OldSalary FROM Employee WHERE SSN = EmpSSN; NewSalary:= OldSalary * (1 + PctRaise); UPDATE Employee SET Salary = NewSalary WHERE SSN = EmpSsn; RETURN NewSalary; Returned value EXCEPTION WHEN No_Data_Found THEN INSERT INTO temp VALUES (EmpSSN, ‘Not found’,Null); RETURN -1; 58 END; PL/SQL Programming -- Anonymous proc. to test the RAISESALARY routine -- Script: raiseSalaryTest Author: VMatos 20-MAY-99 DECLARE theSalary EMPLOYEE.SALARY%TYPE; BEGIN delete from TEMP; theSalary := raiseSalary(123456789, 0.10); insert into TEMP values (123456789, theSalary, NULL); END; / select * from TEMP; clear buffer / 59 PL/SQL Programming PROCEDURE which returns several results CREATE or REPLACE PROCEDURE GetEmpNameSal ( EmpSSN IN number, EmpName OUT varchar2, EmpSalary OUT number ) IS BEGIN select Lname ||', '|| Fname, Salary into EmpName, EmpSalary OUT variables carry results from Employee outside of the procedure where SSN = EmpSSN; EXCEPTION WHEN No_Data_Found THEN insert into TEMP values (EmpSSN, ‘ERROR. Emp not found’,NULL); EmpName:= '***'; EmpSalary:= -1; END; 60 PL/SQL Programming Testing the getEmpNameSal procedure. -- Script: getEmpNameSalTest DECLARE theName TEMP.F3%TYPE; theSalary EMPLOYEE.SALARY%TYPE; BEGIN delete from TEMP; getEmpNameSal (123456789, theName, theSalary); insert into temp values (123456789, theSalary, theName); END; / F1 F2 F3 --------------- ---------- -----------123456789 39930 SMITH, John 61 PL/SQL Programming Anonymous Procedures The following anonymous procedure performs the following tasks: • Executes stored proc. GetEmpNameSal to obtain the name and salary of the employee whose SSN is 123456789. Results are saved into the TEMP table. • Invokes the function RaiseSalary to increase the employee’s salary by 10%. Again, a new line is added to TEMP reporting the new salary value. 62 PL/SQL Programming Anonymous Procedures -- Name: Test2Routines.Sql -- Anonymous Procedure to Test STORED routines -- Uses: proc. GetEmpName,and func. RaiseSalary -- table TEMP (already created with three columns) DECLARE Local memory variables defined to EmpName varchar(20); store the Emp name and salary mSalary number; retrieved using the stored procedure BEGIN DELETE FROM Temp; GetEmpNameSal (123456789, EmpName, mSalary); INSERT INTO Temp VALUES (123456789, mSalary, EmpName); mSalary:= RaiseSalary(123456789, 0.10); INSERT INTO Temp VALUES (123456789, mSalary, EmpName); END; 63 PL/SQL Programming Testing the Anonymous Procedure Running the anonymous script SQL> @ Test2Routines procedure successfully executed SQL> select * from TEMP; F1 --------123456789 123456789 F2 --------30000 33000 F2 ----------------Smith, John Smith, John Results are placed into the TEMP table. 64 PL/SQL Programming Invoking a Stored Function from a SQL Query •The numbers in the BASEBALL table are hard to read. •A function BigBucks(...) is called to facilitate the reading of the big numbers in the table SQL> select * from BASEBALL; PNAME PSALARY -------------------- -----------A. Belle 987654321 K. Griffey 1987654322 B. Bonds 1234567890 D. Cone 123456 P. Butterfingers 900 65 PL/SQL Programming Do this just in case you do not have the BaseBall table! drop table BASEBALL; create table BaseBall (Pname varchar2(20), PSalary varchar2(30)); insert insert insert insert insert into into into into into BaseBall BaseBall BaseBall BaseBall BaseBall values values values values values ('A. ('K. ('B. ('D. ('P. Belle', 987654321); Griffey', 1987654322); Bonds', 1234567890); Cone', 123456); Butterfingers', 900); select * from BaseBall; / 66 PL/SQL Programming Invoking a Stored Function from a SQL Query -- Playball.sql -- This is a small SCRIPT (not an anonymous proc.) -- The pretty function is called from the SQL comnd column psalary format 99999999999 column bigbucks(psalary) format a30 select pname, psalary, BigBucks(psalary) from baseball; SQL> @Playball PNAME PSALARY BIGBUCKS(PSALARY) -------------------- ------------ --------------------A. Belle 987654321 987.65 Millions K. Griffey 1987654322 1.99 Billions B. Bonds 1234567890 1.23 Billions D. Cone 123456 123.46 Thousands P. Butterfingers 900 900.00 Peanuts 67 PL/SQL Programming A Stored Function for Beautifying Big Numbers Create or Replace Function BIGBUCKS ( salary number ) Return varchar IS Billion number := 1000000000; Million number := 1000000; Thousand number := 1000; LPAD( ) adds n spaces on Message varchar(30); on left side of the string Dollars number(6,2); begin if (salary >= Billion) then Dollars:= salary / billion; message:= LPAD(to_char(dollars),8) || ' Billions'; return (message); elsif (salary >= Million) then Dollars:= salary / Million; message:= LPAD(to_char(dollars),8) || ' Millions'; return (message); elsif (salary >= Thousand) then Dollars:= salary / Thousand; message:= LPAD(to_char(dollars),8) || ' Thousands'; return (message); Numeric format else message:= to_char(Salary,'999.00'); message:= LPAD(message,8)||' Peanuts'; return (message); end if; end; 68 PL/SQL Programming Creating a Store Procedure: A dir-like Routine 1. Type the following code into a text file called: dirStor.sql create or replace PROCEDURE dirStor IS firstcol boolean; line varchar2(400); tableName varchar2(20); columnName varchar2(20); CURSOR data IS select table_name, column_name from user_col_comments; 69 PL/SQL Programming BEGIN delete from dirList; line:= ' '; tableName:= ' '; FOR d IN data LOOP if (tableName <> d.table_name) then if (line <> ' ') then line:= line || ');' ; end if; insert into dirList values (line); tableName:= d.table_name; Line:= UPPER(d.table_name) || ' (' ; firstcol:= true; end if; if NOT (firstcol) then line:= Line || ', '; end if; firstcol:= false; line:= line|| LOWER(d.column_Name); END LOOP; line:= line || ');' ; insert into dirList values (line); END; 70 PL/SQL Programming Type-in the following lines into a file called: dir.sql. Put the file in the directory c:\bin\orawin95 -- Script: dir.sql execute dirStor select * from dirList; NOTE: dirList is a user-created table. You need to make the table before using it. Type the following SQL statement: CREATE TABLE dirList ( MyTables VARCHAR2(80) ); 71 PL/SQL Programming An example of how to use the dir routine is given below: SQL> @dir PL/SQL procedure successfully completed. MyTables ---------------------------------------------------------------DEPARTMENT (dname, dnumber, mgrssn, mgrstartdate); DEPENDENT (essn, dependent_name, sex, bdate, relationship); MYLOG (num1, msg); TEMP (F1, F2, F3); PROJECT (pname, pnumber, plocation, dnum); WORKS_ON (essn, pno, hours); 7 rows selected. 72 PL/SQL Programming Writing a Procedure to (a) Securely Insert Works_On records (b) Verify Potential Business Rules The procedure Insert_WorksOn() is invoked to add new records to the Works_On table in a very controlled way. Each call to the function provides the programmers authentication code and data (SSN, ProjNumb, Hour). For example: Result:= Insert_WorkOn(‘Dilbert’,123456789,10,40) If the programmer ‘Dilbert’ is not in the list of peoples authorized to make insertions, the operation is rejected and MYLOG file is update with a rejection message • If the SSN and PNO provided are already in the Works_On table the current insertion is rejected and the log file is updated • The function returns a numeric code 1, -1, -2, etc. to indicate the status of the execution. This number is stored into the variable Result (1: success, negative values: problems). 73 PL/SQL Programming To execute the examples in this section you may need to do the following DML changes. create table WORKS_ON ( essn char(9), pno number, hours number(5,1), CONSTRAINT pk_workson_key PRIMARY KEY (essn, pno)); drop table Valid_Operators; create table VALID_OPERATORS (Operator_Name varchar2(20) ); insert into VALID_OPERATORS values ('Dilbert'); insert into VALID_OPERATORS values ('Calbert'); 74 PL/SQL Programming create or replace FUNCTION Insert_WorksOn ( Programmer_Id EmployeeSsn ProjectNumber WeeklyHours varchar2, number, number, number ) RETURN number IS Programmer_Name varchar(20); Message varchar(70); BEGIN -- First block: Is the programmer allowed to insert records? -- Note: All code goes into one BEGIN...END block. BEGIN select Operator_Name into Programmer_Name from Valid_Operators where Operator_Name = Programmer_Id; EXCEPTION when No_Data_Found then Insert into Mylog values (Programmer_Id, 'ERROR** unauthorized used of function'); RETURN -1; END; -- first block 75 PL/SQL Programming -- INSERTWORKSON cont. -- Second block: Here other conditions could be checked -- before accepting record into the works_on table BEGIN insert into Works_On values (EmployeeSsn, ProjectNumber, WeeklyHours); RETURN 1; EXCEPTION When DUP_VAL_ON_INDEX then Message:= ' Emp ' || to_char(EmployeeSsn) || ' already in proj ' || to_char(ProjectNumber); insert into Mylog values (NULL, Message); RETURN -2; When Others then Message:= ' Emp ' || to_char(EmployeeSsn) || ' not assigned to ' || to_char(ProjectNumber); insert into Mylog values (NULL, Message); RETURN -3; END; -- second block END; 76 PL/SQL Programming --TESTING THE INSERT_WORKSON FUNCTION DECLARE theResultCode NUMBER; BEGIN delete from mylog; theResultCode := Insert_WorksOn ('Dilbert', 123456789, 10,1.2); insert into mylog values ('123456789 workson 10', theResultCode); END; COL1 COL2 ---------------------- ----------------------------------Emp 123456789 already in proj. 10 123456789 workson 10 -2 Mylog ESSN PNO HOURS --------- --------- --------123456789 1 32.5 123456789 2 7.5 123456789 10 1.2 Employee 77 PL/SQL Programming Writing a Secure Procedure to Delete a Works_On record The procedure Delete_WorksOn() is invoked to remove records from the Works_On table. In the function-call the programmers authentication code and the Works_On key field(s) are supplied. For example: in the following call, programmer ‘Dilbert’ asks to remove employee 123456789 from proj. 1. Result:= Delete_WorkOn(‘Dilbert’,123456789,1) • If the programmer ‘Dilbert’ is not authorized to make such a deletion, the operation is rejected and MYLOG file is update with a rejection message • If employee 123456789 is not in the Works_On table the current deletion is rejected and the log file is updated otherwise, the record is eliminated • The function returns a numeric code 1, -1, -2, etc. to indicate the status of the execution. (1: success, negative values: problems). 78 PL/SQL Programming create or replace FUNCTION Delete_WorksOn ( Programmer_Id varchar2, EmployeeSsn number, ProjectNumb number ) RETURN number IS Programmer_Name varchar(20); Message varchar(70); BEGIN -- First block: Verify that programmer is allowed to delete -- Note: all code goes in one BEGIN...END block BEGIN select Operator_Name into Programmer_Name from Valid_Operators where Operator_Name = Programmer_Id; EXCEPTION when No_Data_Found then Message:= 'Programmer not allowed to ' || 'delete Works_On rec.'; Insert into Mylog values(Programmer_Id, Message ); RETURN -1; 79 END; -- first block PL/SQL Programming -- DELETE_WORKSON script cont. ---Second block: Other conditions could be checked here -- before deleting the record BEGIN delete from Works_On where Essn= EmployeeSsn AND Pno = ProjectNumb; if (sql%notfound) then Message:=' ** ' || to_char(EmployeeSsn) || ' / ' || to_char(ProjectNumb) || ' not found '; insert into Mylog values (NULL, Message); RETURN -2; end if; RETURN 1; 80 PL/SQL Programming -- DELETE_WORKSON script cont. ---Second block: Other conditions could be checked here -- before deleting the record EXCEPTION When Others then Message:= ' *** ' || to_char(EmployeeSsn) || ' remains in Works_On'; insert into Mylog values (NULL, Message); RETURN -3; END; -- second block END; 81 PL/SQL Programming -- DELETE_WORKSON script cont. ---Second block: Other conditions could be checked here -- before deleting the record --TESTING THE DELETE_WORKSON FUNCTION DECLARE theCode Number; BEGIN delete from mylog; theCode := delete_WorksOn ('Dilbert', 123456789, 10); insert into mylog values ('After delete ', theCode); END; / select * from mylog; select * from works_on where essn like '123%'; / 82 PL/SQL Programming Writing a Secure Procedure to Update Project records The procedure Update_Project( ) is used to modify existing records in the Project table. Individual records are located using the Pnumber values as search-key. The updating of projects occurs in the context of a function call such as the example bellow. The arguments passed to the function are: Programmer_Id, project number, name, location; and number of responsible department. Result:= Update_Project(‘Dilbert’,1,‘Cerveza XXX’,‘Margarita’,NULL); • • • • • • • Each project record to be updated must include the project number More than one field could be updated in a single function call Project numbers are not changeable (instead delete whole rec. and re-insert with a new number) If the programmer ‘Dilbert’ is authorized to make deletion, the operation is rejected If there is no record for project number 1, the current update is rejected If a field is not going to be updated, the word NULL must be written in the proper column The function returns a numeric code 1, -1, -2, etc. to indicate the status of the execution. 83 PL/SQL Programming Writing a Secure Procedure to Update Project records create or replace FUNCTION Update_Project( Programmer_Id ProjectNumber ProjectName ProjectLocation DepartmentNumber RETURN number IS Programmer_Name varchar2(20); Message varchar2(70); VarPnumber number; number, number, varchar, varchar, number ) 84 PL/SQL Programming Writing a Secure Procedure to Update Project records cont. BEGIN -- First block: Is programmer allowed to update projects? -- NOTE: all code goes in one BEGIN...END block BEGIN select Operator_Name into Programmer_Name from Valid_Operators where Operator_Name = Programmer_Id; EXCEPTION when No_Data_Found then Message:= 'Programmer not allowed to ' || 'update Projects'; Insert into Mylog values (Programmer_Id, Message); RETURN -1; END; -- first block 85 PL/SQL Programming Writing a Secure Procedure to Update Project records cont. -- Second block: Verify there is a project record matching -- Pnumber key. If the field is not NULL, modify using given -- parameter BEGIN select Pnumber into VarPnumber from Project where Pnumber= ProjectNumber; if (ProjectName is not NULL) then update Project set Pname= ProjectName where Pnumber = ProjectNumber; end if; if (ProjectLocation is not NULL) then update Project set Plocation= ProjectLocation where Pnumber = ProjectNumber; End if; if (DepartmentNumber is not NULL) then update Project set Dnum = DepartmentNumber where Pnumber = ProjectNumber; End if; 86 RETURN 1 ; -- success ! PL/SQL Programming Writing a Secure Procedure to Update Project records cont. -- Deal with Update problems here EXCEPTION When No_Data_Found then Message:= ' Project ' || to_char(ProjectNumber) || ' does not exist '; insert into Mylog values (NULL, Message); RETURN -2; When Others then Message:= ' Project ' || to_char(ProjectNumber) || ' can not be updated '; insert into Mylog values (NULL, Message); RETURN -3; END; -- second block END; 87