Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
207 views

Stored Procedures

The document discusses stored procedures in databases, providing examples of how to create and call stored procedures in Java DB and MySQL. Stored procedures allow grouping of SQL statements to perform a specific task and can be executed with different parameters. The examples create stored procedures to show coffee suppliers, get a supplier for a coffee, and raise a coffee's price if below a percentage. It demonstrates creating stored procedures using SQL scripts or JDBC APIs and calling them from Java code.

Uploaded by

deepa01011987
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
207 views

Stored Procedures

The document discusses stored procedures in databases, providing examples of how to create and call stored procedures in Java DB and MySQL. Stored procedures allow grouping of SQL statements to perform a specific task and can be executed with different parameters. The examples create stored procedures to show coffee suppliers, get a supplier for a coffee, and raise a coffee's price if below a percentage. It demonstrates creating stored procedures using SQL scripts or JDBC APIs and calling them from Java code.

Uploaded by

deepa01011987
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 30

Using Stored Procedures

A stored procedure is a group of SQL statements that form a logical unit and perform a particular task, and they are used to encapsulate a set of operations or queries to execute on a database server. For example, operations on an employee database (hire, fire, promote, lookup) could be coded as stored procedures executed by application code. Stored procedures can be compiled and executed with different parameters and results, and they can have any combination of input, output, and input/output parameters. Note that stored procedures are supported by most DBMSs, but there is a fair amount of variation in their syntax and capabilities. Consequently, the tutorial contains two classes, StoredProcedureJavaDBSample and StoredProcedureMySQLSample to demonstrate how to create stored procedures in Java DB and MySQL, respectively. This page covers the following topics:

Overview of Stored Procedures Examples Parameter Modes Creating Stored Procedures in Java DB
o

Creating Stored Procedures in Java DB with SQL Scripts or JDBC API Creating Stored Procedures in Java DB Package Java Class in JAR File

o o

Creating Stored Procedure in MySQL


o

Creating Stored Procedure in MySQL with SQL Scripts or JDBC API

Calling Stored Procedures in Java DB and MySQL

Overview of Stored Procedures Examples

The examples StoredProcedureJavaDBSample.java and StoredProcedureMySQLSample.java c reate and call the following stored procedures:
SHOW_SUPPLIERS:

Prints a result set that contains the names of coffee suppliers and the coffees they supply to The Coffee Break. This stored

procedure does not require any parameters. When the example calls this stored procedure, the example produces output similar to the following:
Acme, Inc.: Colombian_Decaf Acme, Inc.: Colombian Superior Coffee: French_Roast_Decaf Superior Coffee: French_Roast The High Ground: Espresso

GET_SUPPLIER_OF_COFFEE:

Prints the name of the supplier supplierName for the coffee coffeeName. It requires the following parameters:
o o IN coffeeName varchar(32):

The name of the coffee The name of the coffee supplier

OUT supplierName varchar(40):

When the example calls this stored procedure with Colombian as the value for coffeeName, the example produces output similar to the following:
Supplier of the coffee Colombian: Acme, Inc. RAISE_PRICE:

Raises the price of the coffee coffeeName to the price newPrice. If the price increase is greater than the percentage maximumPercentage, then the price is raised by that percentage. This procedure will not change the price if the price newPrice is lower than the original price of the coffee. It requires the following parameters: o IN coffeeName varchar(32): The name of the coffee
o IN maximumPercentage float:

The maximum percentage to raise the

coffee's price
o INOUT newPrice numeric(10,2):

The new price of the coffee. After the RAISE_PRICE stored procedure has been called, this parameter will contain the current price of the coffee coffeeName.

When the example calls this stored procedure with Colombian as the value for coffeeName, 0.10 as the value for maximumPercentage, and 19.99 as the value fornewPrice, the example produces output similar to the following:
Contents of COFFEES table before calling RAISE_PRICE: Colombian, 101, 7.99, 0, 0 Colombian_Decaf, 101, 8.99, 0, 0 Espresso, 150, 9.99, 0, 0 French_Roast, 49, 8.99, 0, 0 French_Roast_Decaf, 49, 9.99, 0, 0 Calling the procedure RAISE_PRICE Value of newPrice after calling RAISE_PRICE: 8.79

Contents of COFFEES table after calling RAISE_PRICE: Colombian, 101, 8.79, 0, 0 Colombian_Decaf, 101, 8.99, 0, 0 Espresso, 150, 9.99, 0, 0 French_Roast, 49, 8.99, 0, 0 French_Roast_Decaf, 49, 9.99, 0, 0

Parameter Modes

The parameter attributes IN (the default), OUT, and INOUT are parameter modes. They define the action of formal parameters. The following table summarizes the information about parameter modes.
Characteristic of Parameter Mode IN OUT INOUT

No; if omitted, then Must it be specified in the the parameter mode of stored procedure Must be specified. the formal parameter definition? is IN. Does the parameter pass a value to the stored Passes values to a procedure or return a stored procedure. value? Returns values to the caller.

Must be specified. Both; passes initial values to a stored procedure; returns updated values to the caller.

Does the formal parameter Formal parameter acts Formal parameter acts act as a constant or a Formal parameter acts like an uninitialized like an initialized variable in the stored like a constant. variable. variable. procedure? Formal parameter Can the formal parameter Formal parameter cannot be used in an be assigned a value in the cannot be assigned a expression; must be stored procedure? value. assigned a value. What kinds of actual parameters (arguments) can be passed to the stored procedure? Formal parameter must be assigned a value.

Actual parameter can be a constant, Actual parameter must Actual parameter must initialized variable, be a variable. be a variable. literal, or expression.

Creating Stored Procedures in Java DB

Note: See the section "CREATE PROCEDURE statement" in Java DB Reference Manual for more information about creating stored procedures in Java DB. Creating and using a stored procedure in Java DB involves the following steps:

1. Create a public static Java method in a Java class : This method performs the required task of the stored procedure. 2. Create the stored procedure: This stored procedure calls the Java method you created.
3.

Package the Java class (that contains the public static Java method you created earlier) in a JAR file. Call the stored procedure with the CALL SQL statement. See the section Calling Stored Procedures in Java DB and MySQL.

4.

Creating Public Static Java Method

The following method, StoredProcedureJavaDBSample.showSuppliers, contains the SQL statements that the stored procedure SHOW_SUPPLIERS calls:
public static void showSuppliers(ResultSet[] rs) throws SQLException { Connection con = DriverManager.getConnection("jdbc:default:connection"); Statement stmt = null; String query = "select SUPPLIERS.SUP_NAME, " + "COFFEES.COF_NAME " + "from SUPPLIERS, COFFEES " + "where SUPPLIERS.SUP_ID = " + "COFFEES.SUP_ID " + "order by SUP_NAME"; stmt = con.createStatement(); rs[0] = stmt.executeQuery(query); }

The SHOW_SUPPLIERS stored procedure takes no arguments. You can specify arguments in a stored procedure by defining them in the method signature of your public static Java method. Note that the method showSuppliers contains a parameter of type ResultSet[]. If your stored procedure returns any number of ResultSet objects, specify one parameter of type ResultSet[] in your Java method. In addition, ensure that this Java method is public and static. Retrieve the Connection object from the URL jdbc:default:connection. This is a convention in Java DB to indicate that the stored procedure will use the currently existing Connection object. Note that the Statement object is not closed in this method. Do not close any Statement objects in the Java method of your stored procedure; if you do so,

the ResultSetobject will not exist when you issue the CALL statement when you call your stored procedure. In order for the stored procedure to return a generated result set, you must assign the result set to an array component of the ResultSet[] parameter. In this example, the generated result set is assigned to the array component rs[0]. The following method is StoredProcedureJavaDBSample.showSuppliers:
public static void getSupplierOfCoffee(String coffeeName, String[] supplierName) throws SQLException { Connection con = DriverManager.getConnection("jdbc:default:connection"); PreparedStatement pstmt = null; ResultSet rs = null; String query = "select SUPPLIERS.SUP_NAME " + "from SUPPLIERS, COFFEES " + "where " + "SUPPLIERS.SUP_ID = COFFEES.SUP_ID " + "and ? = COFFEES.COF_NAME"; pstmt = con.prepareStatement(query); pstmt.setString(1, coffeeName); rs = pstmt.executeQuery(); if (rs.next()) { supplierName[0] = rs.getString(1); } else { supplierName[0] = null; } }

The formal parameter coffeeName has the parameter mode IN. This formal parameter is used like any other parameter in a Java method. Because the formal parametersupplierName has the parameter mode OUT, it must use a one dimensional array data type. Because this method does not produce a result set, the method definition does not contain a parameter of type ResultSet[]. In order to retrieve a value from an OUT formal parameter, you must assign the value to be retrieved to an array component of theOUT formal parameter. In this example, the retrieved name of the coffee supplier is assigned to the array component supplierName[0]. The following is the method signature of the StoredProcedureJavaDBSample.raisePrice

method:

public static void raisePrice( String coffeeName, double maximumPercentage,

BigDecimal[] newPrice) throws SQLException

Because the formal parameter newPrice has the parameter mode INOUT, it must use a one dimensional array data type. Java DB maps the FLOAT and NUMERIC SQL data types to the double and java.math.BigDecimal Java data types, respectively.
Creating Stored Procedures in Java DB with SQL Scripts or JDBC API

Java DB uses the Java programming language for its stored procedures. Consequently, when you define a stored procedure, you specify which Java class to call and where Java DB can find it. The following excerpt from StoredProcedureJavaDBSample.createProcedures creates a stored procedure named SHOW_SUPPLIERS:
public void createProcedures(Connection con) throws SQLException { Statement stmtCreateShowSuppliers = null; // ... String queryShowSuppliers = "CREATE PROCEDURE SHOW_SUPPLIERS() " + "PARAMETER STYLE JAVA " + "LANGUAGE JAVA " + "DYNAMIC RESULT SETS 1 " + "EXTERNAL NAME " + "'com.oracle.tutorial.jdbc." + "StoredProcedureJavaDBSample." + "showSuppliers'"; // ... try { System.out.println("Calling CREATE PROCEDURE"); stmtCreateShowSuppliers = con.createStatement(); // ... } catch (SQLException e) { JDBCTutorialUtilities.printSQLException(e); } finally { if (stmtCreateShowSuppliers != null) { stmtCreateShowSuppliers.close(); } // ... } }

The following list describes the procedure elements you can specify in the CREATE PROCEDURE statement:
PARAMETER STYLE JAVA:

Specifies that the stored procedure uses a parameterpassing convention that conforms to the Java language and the SQL routines specification (currently, JAVA is the only option). LANGUAGE JAVA: Specifies the programming language of the stored procedure (currently, JAVA is the only option).
DYNAMIC RESULT SETS 1:

Specifies the maximum number of result sets retrieved; in this case, it is 1.


EXTERNAL NAME 'com.oracle.tutorial.jdbc.StoredProcedureJavaDBSample.showSuppliers'

pecifies the fully qualified Java method that this stored procedure calls. Note: Java DB must be able to find the method specified here in your class path or in a JAR file directly added to the database. See the following step,Package Java Class in JAR File. The following statement (which is found in StoredProcedureJavaDBSample.createProcedures) creates a stored procedure named GET_SUPPLIERS_OF_COFFEE (line breaks have been added for clarity):
CREATE PROCEDURE GET_SUPPLIER_OF_COFFEE( IN coffeeName varchar(32), OUT supplierName varchar(40)) PARAMETER STYLE JAVA LANGUAGE JAVA DYNAMIC RESULT SETS 0 EXTERNAL NAME 'com.oracle.tutorial.jdbc. StoredProcedureJavaDBSample. getSupplierOfCoffee'

This stored procedure has two formal parameters, coffeeName and supplierName. The parameter specifiers IN and OUT are called parameter modes. They define the action of formal parameters. See Parameter Modes for more information. This stored procedure does not retrieve a result set, so the procedure element DYNAMIC RESULT SETS is 0. The following statement creates a stored procedure named RAISE_PRICE (line breaks have been added for clarity):
CREATE PROCEDURE RAISE_PRICE( IN coffeeName varchar(32), IN maximumPercentage float, INOUT newPrice float) PARAMETER STYLE JAVA

LANGUAGE JAVA DYNAMIC RESULT SETS 0 EXTERNAL NAME 'com.oracle.tutorial.jdbc. StoredProcedureJavaDBSample.raisePrice'

You can use SQL scripts to create stored procedures in Java DB. See the script javadb/create-procedures.sql and the Ant target javadb-create-procedure in thebuild.xml Ant build script.
Package Java Class in JAR File

The Ant build script build.xml contains targets to compile and package the tutorial in a JAR file. At a command prompt, change the current directory to <JDBC tutorial directory>. From this directory, run the following command to compile and package the tutorial in a JAR file:
ant jar

The name of the JAR file is <JDBC

tutorial directory>/lib/JDBCTutorial.jar.

The Ant build script adds the file JDBCTutorial.jar to the class path. You can also specify the location of the JAR file in your CLASSPATH environment variable. This enables Java DB to find the Java method that the stored procedure calls.
Adding JAR File Directly to Database

Java DB looks first in your class path for any required classes, and then in the database. This section shows you how to add JAR files directly to the database. Use the following system procedures to add the JDBCTutorial.jar JAR file to the database (line breaks have been added for clarity):
CALL sqlj.install_jar( '<JDBC tutorial directory>/ lib/JDBCTutorial.jar', 'APP.JDBCTutorial', 0) CALL sqlj.replace_jar( '<JDBC tutorial directory>/ lib/JDBCTutorial.jar', 'APP.JDBCTutorial')"; CALL syscs_util.syscs_set_database_property( 'derby.database.classpath', 'APP.JDBCTutorial')";

Note: The method StoredProcedureJavaDBSample.registerJarFile demonstrates how to call these system procedures. If you call this method, ensure that you have

modified javadb-sample-properties.xml so that the value of the property jar_file is set to the full path name of JDBCTutorial.jar. The install_jar procedure in the SQL schema adds a JAR file to the database. The first argument of this procedure is the full path name of the JAR file on the computer from which this procedure is run. The second argument is an identifier that Java DB uses to refer to the JAR file. (The identifier APP is the Java DB default schema.) Thereplace_jar procedure replaces a JAR file already in the database. The system procedure SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY sets or deletes the value of a property of the database on the current connection. This method sets the property derby.database.classpath to the identifier specified in the install_jar file. Java DB first looks in your Java class path for a class, then it looks inderby.database.classpath.
Creating Stored Procedure in MySQL

Creating and using a stored procedure in Java DB involves the following steps:
1. 2.

Create the stored procedure with an SQL script or JDBC API Call the stored procedure with the CALL SQL statement. See the section Calling Stored Procedures in Java DB and MySQL

Creating Stored Procedure in MySQL with SQL Scripts or JDBC API

MySQL uses a SQL-based syntax for its stored procedures. The following excerpt from the SQL script mysql/create-procedures.sql creates a stored procedure namedSHOW_SUPPLIERS:
SELECT 'Dropping procedure SHOW_SUPPLIERS' AS ' '| drop procedure if exists SHOW_SUPPLIERS| # ... SELECT 'Creating procedure SHOW_SUPPLIERS' AS ' '| create procedure SHOW_SUPPLIERS() begin select SUPPLIERS.SUP_NAME, COFFEES.COF_NAME from SUPPLIERS, COFFEES where SUPPLIERS.SUP_ID = COFFEES.SUP_ID order by SUP_NAME; end|

The DROP PROCEDURE statement deletes that procedure SHOW_SUPPLIERS if it exists. In MySQL, statements in a stored procedure are separated by semicolons. However, a

different delimiter is required to end the create procedure statement. This example uses the pipe (|) character; you can use another character (or more than one character). This character that separates statements is defined in the delimiter attribute in the Ant target that calls this script. This excerpt is from the Ant build file build.xml (line breaks have been inserted for clarity):
<target name="mysql-create-procedure"> <sql driver="${DB.DRIVER}" url="${DB.URL}" userid="${DB.USER}" password="${DB.PASSWORD}" classpathref="CLASSPATH" print="true" delimiter="|" autocommit="false" onerror="abort"> <transaction src="./sql/${DB.VENDOR}/ create-procedures.sql"> </transaction> </sql> </target>

Alternatively, you can use the DELIMITER SQL statement to specify a different delimiter character. The CREATE PROCEDURE statement consists of the name of the procedure, a commaseparated list of parameters in parentheses, and SQL statements within the BEGIN andEND keywords. You can use the JDBC API to create a stored procedure. The following method, StoredProcedureMySQLSample.createProcedureShowSuppliers, performs the same tasks as the previous script:
public void createProcedureShowSuppliers() throws SQLException { String createProcedure = null; String queryDrop = "DROP PROCEDURE IF EXISTS SHOW_SUPPLIERS"; createProcedure = "create procedure SHOW_SUPPLIERS() " + "begin " + "select SUPPLIERS.SUP_NAME, " + "COFFEES.COF_NAME " + "from SUPPLIERS, COFFEES " + "where SUPPLIERS.SUP_ID = " + "COFFEES.SUP_ID " +

"order by SUP_NAME; " + "end"; Statement stmt = null; Statement stmtDrop = null; try { System.out.println("Calling DROP PROCEDURE"); stmtDrop = con.createStatement(); stmtDrop.execute(queryDrop); } catch (SQLException e) { JDBCTutorialUtilities.printSQLException(e); } finally { if (stmtDrop != null) { stmtDrop.close(); } } try { stmt = con.createStatement(); stmt.executeUpdate(createProcedure); } catch (SQLException e) { JDBCTutorialUtilities.printSQLException(e); } finally { if (stmt != null) { stmt.close(); } } }

Note that the delimiter has not been changed in this method. The stored procedure SHOW_SUPPLIERS generates a result set, even though the return type of the method createProcedureShowSuppliers is void and the method does not contain any parameters. A result set is returned when the stored procedure SHOW_SUPPLIERS is called with the method CallableStatement.executeQuery:
CallableStatement cs = null; cs = this.con.prepareCall("{call SHOW_SUPPLIERS}"); ResultSet rs = cs.executeQuery();

The following excerpt from the method StoredProcedureMySQLSample.createProcedureGetSupplierOfCoffee contains the SQL query that creates a stored procedure named GET_SUPPLIER_OF_COFFEE:
public void createProcedureGetSupplierOfCoffee() throws SQLException { String createProcedure = null; // ... createProcedure = "create procedure GET_SUPPLIER_OF_COFFEE(" +

"IN coffeeName varchar(32), " + "OUT supplierName varchar(40)) " + "begin " + "select SUPPLIERS.SUP_NAME into " + "supplierName " + "from SUPPLIERS, COFFEES " + "where SUPPLIERS.SUP_ID = " + "COFFEES.SUP_ID " + "and coffeeName = COFFEES.COF_NAME; " + "select supplierName; " + "end"; // ... }

This stored procedure has two formal parameters, coffeeName and supplierName. The parameter specifiers IN and OUT are called parameter modes. They define the action of formal parameters. See Parameter Modes for more information. The formal parameters are defined in the SQL query, not in the methodcreateProcedureGetSupplierOfCoffee. To assign a value to the OUT parameter supplierName, this stored procedure uses a SELECT statement. The following excerpt from the method StoredProcedureMySQLSample.createProcedureRaisePrice contains the SQL query that creates a stored procedure named RAISE_PRICE:
public void createProcedureRaisePrice() throws SQLException { String createProcedure = null; // ... createProcedure = "create procedure RAISE_PRICE(" + "IN coffeeName varchar(32), " + "IN maximumPercentage float, " + "INOUT newPrice numeric(10,2)) " + "begin " + "main: BEGIN " + "declare maximumNewPrice " + "numeric(10,2); " + "declare oldPrice numeric(10,2); " + "select COFFEES.PRICE into oldPrice " + "from COFFEES " + "where COFFEES.COF_NAME " + "= coffeeName; " + "set maximumNewPrice = " + "oldPrice * (1 + " + "maximumPercentage); " + "if (newPrice > maximumNewPrice) " + "then set newPrice = " + "maximumNewPrice; " + "end if; " +

"if (newPrice <= oldPrice) " + "then set newPrice = oldPrice; " + "leave main; " + "end if; " + "update COFFEES " + "set COFFEES.PRICE = newPrice " + "where COFFEES.COF_NAME " + "= coffeeName; " + "select newPrice; " + "END main; " + "end"; } // ...

The stored procedure assigns a value to the INOUT parameter newPrice with the SET and SELECT statements. To exit the stored procedure, the stored procedure first encloses the statements in a BEGIN ... END block labeled main. To exit the procedure, the method uses the statement leave main.
Calling Stored Procedures in Java DB and MySQL

The following excerpt from method runStoredProcedures, calls the stored procedure SHOW_SUPPLIERS and prints the generated result set:
cs = this.con.prepareCall("{call SHOW_SUPPLIERS()}"); ResultSet rs = cs.executeQuery(); while (rs.next()) { String supplier = rs.getString("SUP_NAME"); String coffee = rs.getString("COF_NAME"); System.out.println(supplier + ": " + coffee); }

Note: As with Statement objects, to call the stored procedure, you can call execute, executeQuery, or executeUpdate depending on how many ResultSet objects the procedure returns. However, if you are not sure how many ResultSet objects the procedure returns, call execute. Calling the stored procedure SHOW_SUPPLIERS is demonstrated in the section Creating Stored Procedure with JDBC API in MySQL. The following excerpt from method runStoredProcedures, calls the stored procedure GET_SUPPLIER_OF_COFFEE:
cs = this.con.prepareCall("{call GET_SUPPLIER_OF_COFFEE(?, ?)}"); cs.setString(1, coffeeNameArg); cs.registerOutParameter(2, Types.VARCHAR); cs.executeQuery();

String supplierName = cs.getString(2);

The interface CallableStatement extends PreparedStatement. It is used to call stored procedures. Specify values for IN parameters (such as coffeeName in this example) just like you would with a PreparedStatement object by calling the appropriate setter method. However, if a stored procedure contains an OUT parameter, you must register it with the registerOutParameter method. The following excerpt from the method runStoredProcedures, calls the stored procedure RAISE_PRICE:
cs = this.con.prepareCall("{call RAISE_PRICE(?,?,?)}"); cs.setString(1, coffeeNameArg); cs.setFloat(2, maximumPercentageArg); cs.registerOutParameter(3, Types.NUMERIC); cs.setFloat(3, newPriceArg); cs.execute();

Because the parameter newPrice (the third parameter in the procedure RAISE_PRICE) has the parameter mode INOUT, you must both specify its value by calling the appropriate setter method and register it with the registerOutParameter method.
Dear Developer, I want to create simple stored procedure in oracle with passing parameter and creating select statement with where condition and with if..else clause. I am new in oracle. Its grateful for me if any body help me creating simple procedure in oracle database.

SQL> CREATE OR REPLACE PROCEDURE AddNewEmployee ( p_FirstName employee.first_name%TYPE, p_LastName employee.last_name%TYPE, p_Salary employee.salary%TYPE) AS BEGIN INSERT INTO employee (ID, first_name, last_name, salary) VALUES (student_sequence.nextval, p_FirstName, p_LastName, p_Salary); COMMIT; END AddNewEmployee; /

SQL> SQL> SQL> SQL> 2 LL, 3 4 5 6 7 8 9 10 11

-- create demo table create table Employee( ID VARCHAR2(4 BYTE) First_Name Last_Name Start_Date End_Date Salary City Description ) / VARCHAR2(10 BYTE), VARCHAR2(10 BYTE), DATE, DATE, Number(8,2), VARCHAR2(10 BYTE), VARCHAR2(15 BYTE)

NOT NU

Table created. SQL> SQL> -- prepare data SQL> insert into Employee(ID, First_Name, Last_Name, Sta rt_Date, End_Date, Salary, City, Description) 2 values ('01','Jason', 'Martin', to_ date('19960725','YYYYMMDD'), to_date('20060725','YYYYMMDD '), 1234.56, 'Toronto', 'Programmer') 3 / 1 row created. SQL> insert into Employee(ID, First_Name, Last_Name, Sta rt_Date, End_Date, Salary, City, Description) 2 values('02','Alison', 'Mathews', to_ date('19760321','YYYYMMDD'), to_date('19860221','YYYYMMDD '), 6661.78, 'Vancouver','Tester') 3 /

1 row created. SQL> insert into Employee(ID, First_Name, Last_Name, Sta rt_Date, End_Date, Salary, City, Description) 2 values('03','James', 'Smith', to_ date('19781212','YYYYMMDD'), to_date('19900315','YYYYMMDD '), 6544.78, 'Vancouver','Tester') 3 / 1 row created. SQL> insert into Employee(ID, First_Name, Last_Name, Sta rt_Date, End_Date, Salary, City, Description) 2 values('04','Celia', 'Rice', to_ date('19821024','YYYYMMDD'), to_date('19990421','YYYYMMDD '), 2344.78, 'Vancouver','Manager') 3 / 1 row created. SQL> insert into Employee(ID, First_Name, Last_Name, Sta rt_Date, End_Date, Salary, City, Description) 2 values('05','Robert', 'Black', to_ date('19840115','YYYYMMDD'), to_date('19980808','YYYYMMDD '), 2334.78, 'Vancouver','Tester') 3 / 1 row created. SQL> insert into Employee(ID, First_Name, Last_Name, Sta rt_Date, End_Date, Salary, City, Description) 2 values('06','Linda', 'Green', to_

date('19870730','YYYYMMDD'), to_date('19960104','YYYYMMDD '), 4322.78,'New York', 'Tester') 3 / 1 row created. SQL> insert into Employee(ID, First_Name, Last_Name, Sta rt_Date, End_Date, Salary, City, Description) 2 values('07','David', 'Larry', to_ date('19901231','YYYYMMDD'), to_date('19980212','YYYYMMDD '), 7897.78,'New York', 'Manager') 3 / 1 row created. SQL> insert into Employee(ID, First_Name, Last_Name, Sta rt_Date, End_Date, Salary, City, Description) 2 values('08','James', 'Cat', to_ date('19960917','YYYYMMDD'), to_date('20020415','YYYYMMDD '), 1232.78,'Vancouver', 'Tester') 3 / 1 row created. SQL> SQL> SQL> SQL> -- display data in the table SQL> select * from Employee 2 / ID FIRST_NAME LAST_NAME START_DAT END_DATE SALARY CITY DESCRIPTION ---- -------------------- -------------------- ----------------- ---------- ---------- ---------------

01 Jason 25-JUL-06 02 Alison 21-FEB-86 03 James 15-MAR-90 04 Celia 21-APR-99 05 Robert 08-AUG-98 06 Linda 04-JAN-96 07 David 12-FEB-98 08 James 15-APR-02

1234.56 6661.78 6544.78 2344.78 2334.78 4322.78 7897.78 1232.78

Martin Toronto Programmer Mathews Vancouver Tester Smith Vancouver Tester Rice Vancouver Manager Black Vancouver Tester Green New York Tester Larry New York Manager Cat Vancouver Tester

25-JUL-96 21-MAR-76 12-DEC-78 24-OCT-82 15-JAN-84 30-JUL-87 31-DEC-90 17-SEP-96

8 rows selected. SQL> SQL> SQL> SQL> create sequence student_sequence; Sequence created. SQL> SQL> CREATE OR REPLACE PROCEDURE AddNewEmployee ( 2 p_FirstName employee.first_name%TYPE, 3 p_LastName employee.last_name%TYPE, 4 p_Salary employee.salary%TYPE) AS 5 BEGIN 6 INSERT INTO employee (ID, first_name, last_name, 7 salary) 8 VALUES (student_sequence.nextval, p_FirstName, p _LastName, 9 p_Salary);

10 11 12 13

COMMIT; END AddNewEmployee; /

SP2-0804: Procedure created with compilation warnings SQL> SQL> --Calling a procedure SQL> DECLARE 2 v_NewFirstName employee.first_name%TYPE := 'M argaret'; 3 v_NewLastName employee.last_name%TYPE := 'M ason'; 4 v_NewSalary employee.salary%TYPE := 2000; 5 BEGIN 6 -- Add Margaret Mason to the database. 7 AddNewEmployee(v_NewFirstName, v_NewLastName, v_Ne wSalary); 8 END; 9 / PL/SQL procedure successfully completed. SQL> SQL> SQL> SQL> select * from employee; ID FIRST_NAME LAST_NAME START_DAT END_DATE SALARY CITY DESCRIPTION ---- -------------------- -------------------- ----------------- ---------- ---------- --------------01 Jason Martin 25-JUL-96 25-JUL-06 1234.56 Toronto Programmer 02 Alison Mathews 21-MAR-76 21-FEB-86 6661.78 Vancouver Tester

03 James 15-MAR-90 6544.78 04 Celia 21-APR-99 2344.78 05 Robert 08-AUG-98 2334.78 06 Linda 04-JAN-96 4322.78 07 David 12-FEB-98 7897.78 08 James 15-APR-02 1232.78 1 Margaret 2000 9 rows selected.

Smith Vancouver Rice Vancouver Black Vancouver Green New York Larry New York Cat Vancouver Mason

12-DEC-78 Tester 24-OCT-82 Manager 15-JAN-84 Tester 30-JUL-87 Tester 31-DEC-90 Manager 17-SEP-96 Tester

SQL> SQL> drop sequence student_sequence; Sequence dropped. SQL> SQL> SQL> SQL> -- clean the table SQL> drop table Employee 2 / Table dropped.

27.6.2.Creating a Stored Procedure for table update

SQL> SQL> SQL> SQL> SQL> SQL> 2 3 4 5 6 7 8 9 10 11

-- create demo table create table Employee( ID VARCHAR2(4 BYTE) First_Name VARCHAR2(10 BYTE), Last_Name VARCHAR2(10 BYTE), Start_Date DATE, End_Date DATE, Salary Number(8,2), City VARCHAR2(10 BYTE), Description VARCHAR2(15 BYTE) ) /

NOT NULL primary key,

Table created.

SQL> SQL> -- prepare data SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_ 2 values ('01','Jason', 'Martin', to_date('19960725','YYYYMMDD'), to_d 3 / 1 row created.

SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_ 2 values('02','Alison', 'Mathews', to_date('19760321','YYYYMMDD'), to_d 3 / 1 row created.

SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_ 2 values('03','James', 'Smith', to_date('19781212','YYYYMMDD'), to_d 3 / 1 row created.

SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_ 2 values('04','Celia', 'Rice', to_date('19821024','YYYYMMDD'), to_d 3 / 1 row created.

SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_ 2 values('05','Robert', 'Black', to_date('19840115','YYYYMMDD'), to_d 3 / 1 row created.

SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_ 2 values('06','Linda', 'Green', to_date('19870730','YYYYMMDD'), to_d 3 / 1 row created.

SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_ 2 values('07','David', 'Larry', to_date('19901231','YYYYMMDD'), to_d 3 / 1 row created.

SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_ 2 values('08','James', 'Cat', to_date('19960917','YYYYMMDD'), to_d 3 / 1 row created. SQL> SQL> SQL> SQL> -- display data in the table SQL> select * from Employee 2 / ID ---01 02 03 04 05 06 07 08 FIRST_NAME ---------Jason Alison James Celia Robert Linda David James LAST_NAME ---------Martin Mathews Smith Rice Black Green Larry Cat START_DAT --------25-JUL-96 21-MAR-76 12-DEC-78 24-OCT-82 15-JAN-84 30-JUL-87 31-DEC-90 17-SEP-96 END_DATE SALARY CITY --------- ---------- ---------25-JUL-06 1234.56 Toronto 21-FEB-86 6661.78 Vancouver 15-MAR-90 6544.78 Vancouver 21-APR-99 2344.78 Vancouver 08-AUG-98 2334.78 Vancouver 04-JAN-96 4322.78 New York 12-FEB-98 7897.78 New York 15-APR-02 1232.78 Vancouver DESCRIPTION --------------Programmer Tester Tester Manager Tester Tester Manager Tester

8 rows selected. SQL> SQL> 2 3 4 5 CREATE OR REPLACE PROCEDURE emp_change_s (i_emp_id IN VARCHAR2) AS BEGIN UPDATE employee set City = 'New' WHERE id = i_emp_id; END emp_change_s; /

Procedure created. SQL> SQL> call emp_change_s('01'); Call completed. SQL> SQL> select * from employee; ID ---01 02 FIRST_NAME ---------Jason Alison LAST_NAME ---------Martin Mathews START_DAT --------25-JUL-96 21-MAR-76 END_DATE SALARY CITY --------- ---------- ---------25-JUL-06 1234.56 New 21-FEB-86 6661.78 Vancouver DESCRIPTION --------------Programmer Tester

03 04 05 06 07 08

James Celia Robert Linda David James

Smith Rice Black Green Larry Cat

12-DEC-78 24-OCT-82 15-JAN-84 30-JUL-87 31-DEC-90 17-SEP-96

15-MAR-90 21-APR-99 08-AUG-98 04-JAN-96 12-FEB-98 15-APR-02

6544.78 2344.78 2334.78 4322.78 7897.78 1232.78

Vancouver Vancouver Vancouver New York New York Vancouver

Tester Manager Tester Tester Manager Tester

8 rows selected. SQL> SQL> SQL> -- clean the table SQL> drop table Employee 2 / Table dropped.

27.6.3.Call a trigger in procedure


CREATE TABLE authors ( 2 id NUMBER PRIMARY KEY, 3 first_name VARCHAR2(50), 4 last_name VARCHAR2(50) 5 ); Table created. SQL> INSERT INTO authors (id, first_name, last_name) 2 VALUES (1, 'Marlene', 'Theriault'); 1 row created. SQL> SQL> INSERT INTO authors (id, first_name, last_name) 2 VALUES (2, 'Rachel', 'Carmichael'); 1 row created. SQL> SQL> INSERT INTO authors (id, first_name, last_name) 2 VALUES (3, 'James', 'Viscusi'); 1 row created. SQL> SQL> SQL> COMMIT; Commit complete. SQL> SQL> PROMPT

SQL> PROMPT ** Create an BEFORE UPDATE trigger on the AUTHORS table ** Create an BEFORE UPDATE trigger on the AUTHORS table SQL> PROMPT SQL> SQL> 2 3 4 5 6 7 8 9 10 11 CREATE OR REPLACE TRIGGER author_trig BEFORE UPDATE OF first_name ON authors FOR EACH ROW BEGIN DBMS_OUTPUT.PUT_LINE('First Name ' ||:OLD.first_name ||' has change to ' ||:NEW.first_name); END; /

Trigger created. SQL> SQL> PROMPT SQL> PROMPT ** Create a procedure that will cause the author_trig to fire ** Create a procedure that will cause the author_trig to fire SQL> PROMPT SQL> SQL> 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 CREATE OR REPLACE PROCEDURE author_first_name_upd ( i_author_id IN AUTHORS.ID%TYPE, i_first_name IN AUTHORS.FIRST_NAME%TYPE) IS BEGIN UPDATE authors a SET a.first_name = UPPER(i_first_name) WHERE a.id = i_author_id; EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE(sqlerrm); END; /

Procedure created. SQL> SQL> SET ESCAPE OFF SQL> SQL> SQL> drop table authors; Table dropped. SQL>

SQL>

27.6.5.Exceptions in Subprograms
SQL> SQL> SQL> SQL> SQL> 2 3 4 5 6 7 8 9 10 11 12 13

CREATE OR REPLACE PROCEDURE RaiseError ( p_Raise IN BOOLEAN := TRUE, p_ParameterA OUT NUMBER) AS BEGIN p_ParameterA := 7; IF p_Raise THEN RAISE DUP_VAL_ON_INDEX; ELSE RETURN; END IF; END RaiseError; /

SP2-0804: Procedure created with compilation warnings SQL> DECLARE 2 v_TempVar NUMBER := 1; 3 BEGIN 4 DBMS_OUTPUT.put_line('Initial value'); 5 RaiseError(FALSE, v_TempVar); 6 7 DBMS_OUTPUT.put_line('Value after successful call'); 8 9 v_TempVar := 2; 10 DBMS_OUTPUT.put_line('Value before 2nd call'); 11 RaiseError(TRUE, v_TempVar); 12 EXCEPTION 13 WHEN OTHERS THEN 14 DBMS_OUTPUT.put_line('Value after unsuccessful call'); 15 END; 16 / Initial value Value after successful call Value before 2nd call Value after unsuccessful call PL/SQL procedure successfully completed. SQL> SQL>

27.6.6.Forward Declarations

SQL> SQL> SQL> 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

DECLARE v_TempVal BINARY_INTEGER := 5; -- Forward declaration of procedure B. PROCEDURE B(p_Counter IN OUT BINARY_INTEGER); PROCEDURE A(p_Counter IN OUT BINARY_INTEGER) IS BEGIN IF p_Counter > 0 THEN B(p_Counter); p_Counter := p_Counter - 1; END IF; END A; PROCEDURE B(p_Counter IN OUT BINARY_INTEGER) IS BEGIN p_Counter := p_Counter - 1; A(p_Counter); END B; BEGIN B(v_TempVal); END; /

PL/SQL procedure successfully completed. SQL> SQL>

27.6.7.Using stored functions in SQL statements, function getName


SQL> SQL> SQL> create table company( 2 product_id number(4) not null, 3 company_id NUMBER(8) not null, 4 company_short_name varchar2(30) not null, 5 company_long_name varchar2(60) 6 ); Table created. SQL> insert into company values(1,1001,'A Inc.','Long Name A Inc.'); 1 row created. SQL> insert into company values(1,1002,'B Inc.','Long Name B Inc.'); 1 row created.

SQL> insert into company values(1,1003,'C Inc.','Long Name C Inc.'); 1 row created. SQL> insert into company values(2,1004,'D Inc.','Long Name D Inc.'); 1 row created. SQL> insert into company values(2,1005,'E Inc.','Long Name E Inc.'); 1 row created. SQL> insert into company values(2,1006,'F Inc.','Long Name F Inc.'); 1 row created. SQL> SQL> SQL> SQL> 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

CREATE OR REPLACE FUNCTION getName (ip_product_id NUMBER, ip_company_id NUMBER) RETURN VARCHAR2 IS v_name VARCHAR2(120); BEGIN SELECT 'Org Name: (Short) '||company_short_name||' (Long) '||company_long_name INTO v_name FROM company WHERE product_id = ip_product_id AND company_id = ip_company_id; RETURN (v_name); END getName; /

Function created. SQL> SQL> SELECT getName(product_id,company_id) "Formatted Org Name" 2 FROM company 3 ORDER BY product_id,company_id; Formatted Org Name ---------------------------------------------------------------------Org Name: (Short) A Inc. (Long) Long Name A Inc. Org Name: (Short) B Inc. (Long) Long Name B Inc. Org Name: (Short) C Inc. (Long) Long Name C Inc. Org Name: (Short) D Inc. (Long) Long Name D Inc. Org Name: (Short) E Inc. (Long) Long Name E Inc. Org Name: (Short) F Inc. (Long) Long Name F Inc. 6 rows selected.

SQL> SQL> drop table company; Table dropped.

27.6.8.Create procedure for AUTHID CURRENT_USER


SQL> SQL> CREATE TABLE customer 2 (customer_id NUMBER(7), 3 customer_name VARCHAR2(50), 4 phone VARCHAR2(15), 5 address VARCHAR2(400), 6 city VARCHAR2(35), 7 state VARCHAR2(30), 8 country VARCHAR2(30), 9 zip_code VARCHAR2(10), 10 credit_rating VARCHAR2(9), 11 sales_rep_id NUMBER(7), 12 region_id NUMBER(7), 13 comments VARCHAR2(255), 14 preferred_customer VARCHAR2(1) DEFAULT 'N' NOT NULL, 15 shipping_method VARCHAR2(1) DEFAULT 'M' NOT NULL); Table created. SQL> SQL> INSERT INTO customer VALUES (201, 'Jane', 1 row created. SQL> INSERT INTO customer VALUES (202, 'Todd', 1 row created. SQL> INSERT INTO customer VALUES (203, 'Sharon', 1 row created. SQL> INSERT INTO customer VALUES (204, 'Hong', 1 row created.

'111-1111', '7 AVE','SAO', NULL, 'BRAZIL

'222-2222', '6 BLVD.','OSAKA', NULL, 'JA

'333-3333', '1 STREET', 'NEW DELHI', NUL

'444-4444', '2 STREET','SEATTLE', 'WASHI

SQL> INSERT INTO customer VALUES (205, 'Anderson','555-5555', '5 ROAD', 'HONG KONG', NULL, 1 row created. SQL> INSERT INTO customer VALUES (206, 'Bob', 1 row created. SQL> INSERT INTO customer VALUES (207, 'Cat',

'666-6666', '1 ROAD','CANNES', NULL, 'FR

'777-7777', '6 STREET','LAGOS', NULL, 'N

1 row created. SQL> INSERT INTO customer VALUES (208, 'Doge', 1 row created. SQL> INSERT INTO customer VALUES (209, 'Black', 1 row created. SQL> INSERT INTO customer VALUES (210, 'Red', 1 row created. SQL> INSERT INTO customer VALUES (211, 'Ted', 1 row created. SQL> INSERT INTO customer VALUES (212, 'Homas', 1 row created. SQL> INSERT INTO customer VALUES (213, 'Look', 1 row created. SQL> INSERT INTO customer VALUES (214, 'Yellow', 1 row created. SQL> INSERT INTO customer VALUES (215, 'White', 1 row created. SQL> SQL> SQL> SQL> SQL> 2 3 4 5 6 7 8 9 10 11 '337-3892', '6 YEK','SAINT PETERSBURG', '555-7171', '4 STREET','BUFFALO', 'NY', '124-1234', '5 COR','ALEXANDRIA', NULL,

'888-8888', '4 RASSE', 'STUTTGART', NULL

'999-9999', '2 MAR','SAN PEDRO DE MACON'

'000-0000', '3 ARO','NOGALES', NULL, 'ME

'123-1231', '7 MOD', 'PRAGUE',NULL, 'CZE

'555-6281', '4 STREET', 'SAN FRANCISCO',

CREATE OR REPLACE PROCEDURE display_customers AUTHID CURRENT_USER IS CURSOR cur_cust IS SELECT customer_id, customer_name FROM customer; BEGIN FOR cur_cust_rec IN cur_cust LOOP DBMS_OUTPUT.PUT_LINE('Customer Id: ' || cur_cust_rec.customer_id || CHR(9) || ' END LOOP; END display_customers; /

Procedure created. SQL> SQL> drop table customer;

Table dropped.

You might also like