Procedural SQL – Part of Chapter 7 7 Procedural SQL Shortcomings of SQL SQL doesn’t support execution of a stored set of procedures based on some logical condition. SQL fails to support the looping operations. No handling of sequence of operations 7 Solutions Embedded SQL Shared Code To remedy the above shortcomings, SQL statements can be inserted within the procedural programming language The embedded SQL approach involves the duplication of application code in many programs. Critical code is isolated and shared by all application programs. This approach allows better maintenance and logic control. Procedural SQL (Oracle’s version of persistent stored modules) Procedural SQL Procedural SQL 7 Procedural SQL allows the use of procedural code and SQL statements that are stored within the database. The procedural code is executed by the DBMS when it is invoked by the end user. End users can use procedural SQL (PL/SQL) to create: Anonymous PL/SQL blocks Triggers Stored procedures PL/SQL functions Anonymous PL/SQL Block Examples 7 SHOW ERRORS Can help diagnose errors found in PL/SQL blocks 7 Yields additional debugging information whenever an error is generated after an PL/SQL block is created or executed Anonymous PL/SQL Block with Variables and Loops 7 Procedural SQL Triggers 7 A trigger is procedural SQL code that is automatically invoked by the RDBMS upon the occurrence of a data manipulation event. A trigger is always invoked before or after a data row is selected, inserted, or updated. A trigger is always associated with a database table. Each database table may have one or more triggers. A trigger is executed as part of the transaction that triggered it. Procedural SQL 7 Role of triggers Triggers can be used to enforce constraints that cannot be enforced at the design and implementation levels. Triggers add functionality by automating critical actions and providing appropriate warnings and suggestions for remedial action. Triggers can be used to update table values, insert records in tables, and call other stored procedures. Triggers add processing power to the RDBMS and to the database system. Triggers Oracle recommends triggers for: 7 Auditing purposes (creating audit logs) Automatic generation of derived column values Enforcement of business or security constraints Creating replica tables for backup purposes The Revised PRODUCT Table 7 Procedural SQL Syntax to create a trigger in ORACLE 7 CREATE OR REPLACE TRIGGER <trigger_name> [BEFORE/AFTER][DELETE/INSERT/UPDATE OF <column_name] ON <table_name> [FOR EACH ROW] BEGIN PL/SQL instructions; …………… END; Creating Trigger 7 To ensure academic year doesn’t get out of synch with credits earned CREATE OR REPLACE TRIGGER trg_cred_updated AFTER UPDATE OF credits ON students BEGIN UPDATE students SET Year = ‘Sr’ WHERE credits >= 90; … also do juniors, sophs END; Creation of the Oracle Trigger for the PRODUCT Table 7 The P_REORDER Value Mismatch 7 The Second Version of the PRODUCT_REORDER Trigger 7 Figure 7.34 7 Variation on Figure 7.35 The P_REORDER Flag Has Not Been Properly Set After Increasing the P_ONHAND Value 7 Variation on Figure 7.36 The Third Version of the Product Reorder Trigger 7 Figure 7.37 Execution of the Third Trigger Version 7 Figure 7.38 Procedural SQL Stored Procedures 7 A stored procedure is a named collection of procedural and SQL statements. Stored procedures are stored in the database and invoked by name. Stored procedures are executed as a unit. The use of stored procedures reduces network traffic, thus improving performance. Stored Procedures: Advantages Substantially reduce network traffic and increase performance 7 No transmission of individual SQL statements over network Help reduce code duplication by means of code isolation and code sharing Minimize chance of errors and cost of application development and maintenance Procedural SQL Syntax to create a stored procedure 7 CREATE OR REPLACE PROCEDURE procedure_name (argument IN/OUT data-type, etc) IS/AS BEGIN DECLARE variable name and data type PL/SQL or SQL statements; END; Syntax to invoke a stored procedure EXEC store_procedure_name (parameter, parameter, …) Creating and Invoking A Simple Stored Procedure 7 No Longer a Figure The PROD_SALE Stored Procedure 7 No Longer a Figure Executing the PROD_SALE Stored Procedure 7 No Longer a Figure Creating the PRC_PROD_DISCOUNT Stored Procedure 7 Results of the PRC_PROD_DISCOUNT Stored Procedure 7 Stored Procedure with Parameter 7 CREATE OR REPLACE PROCEDURE prc_prod_discount2 (wpi IN NUMBER) AS BEGIN IF ((wpi <= 0) OR (wpi >= 1)) THEN – validate param DBMS_OUTPUT.PUT_LINE(‘Error – bad pct’); ELSE UPDATE product SET p_discount = p_discount + wpi WHERE p_onhand >= p_min * 2; DBMS_OUTPUT.PUT_LINE(‘Update Successful’); END IF; END; / Calling Stored Procedure With Parameter SQL> EXEC prc_prod_discount2 (1.5); -- will get error 7 SQL> EXEC prc_prod_discount2 (.05); -- will work like original The PRC_CUS_ADD Stored Procedure 7 The PRC_INV_ADD and PRC_LINE_ADD Stored Procedures 7 Testing the PRC_INV_ADD and PRC_LINE_ADD Procedures 7 Cursor Processing Commands 7 Cursor Attributes 7 Stored Procedures 7 Advantage – can be used to encapsulate an entire business transaction – group statements together as a transaction and don’t let them be separated Advantage – code resides at the DB and is executed at the DB – less communication – faster processing Advantage – reduce redundant code – since code that Would be repeated is in a procedure that can be written once and called multiple times. Used 1) when transaction involves updating multiple tables OR 2) for complex business rules or constraints Procedural SQL PL/SQL Stored Functions 7 A stored function is a named group of procedural and SQL statements that returns a value. Syntax to create a function: CREATE FUNCTION function_name (argument IN data-type, etc) RETURN data-type AS BEGIN PL/SQL statements; RETURN (value); …… END; Stored procedures can be called from triggers or stored procedures Embedded SQL SQL code embedded within host language (COBOL, C++, ASP, Java, Visual Basic, …) program 7 Embedded SQL Framework: A standard syntax to identify SQL statements (EXEC SQL/ END-EXEC) A standard syntax to identify host variables (:varname for host program variables within SQL statements) A communication area used to exchange status and error information between SQL and the host language (SQLCODE and SQLSTATE variables) Alternative interface – programs use a Call Level Interface (CLI) in which the programmer uses an Application Programming Interface (API) such as ODBC (Windows) or JDBC (Java) Static SQL Embedded SQL in which the programmer used predefined SQL statements and parameters 7 End users of programs are limited to actions that were specified in application programs SQL statements will not change while application is running Using (Static) Embedded SQL Programmer writes embedded SQL inside host language Preprocessor transforms embedded SQL into specialized procedure calls that are DBMS and language-specific 7 Preprocessor provided by the DBMS vendor The program is compiled using host language compiler Compiler creates object code module with DBMS procedure calls Object code is linked to respective library modules and generates executable Binds DBMS procedure calls to DBMS run-time libraries. Binding process typically creates an “access plan” module that contains instructions to run the embedded code at run time Executable is run and embedded SQL statements retrieve data from the DB Using (Static) Embedded SQL 7 EXEC SQL SQL statement END-EXEC To be useful, statement probably can’t do the same thing every time the program is run – need variables Variables declared in host language Inside SQL statement, precede with : E.g. EXEC SQL DELETE FROM students WHERE stdID = :toDel; END-EXEC; E.g. EXEC SQL SELECT max(GPA) INTO :maxGpa FROM students; END_EXEC; Using Static Embedded SQL 7 As with PL/SQL, embedded SQL requires the use of cursors to hold multi-results queries Declare cursor EXEC SQL DECLARE StdCursor FOR SELECT stdID, LName, FName FROM Students WHERE major = ‘Dart’; END-EXEC Open cursor EXEC SQL OPEN StdCursor; END-EXEC Fetch next record EXEC SQL FETCH StdCursor INTO :stdID, :last, :first; END-EXEC IF SQLCODE = 0 THEN … do whatever is necessary Dynamic SQL 7 SQL statement is not known in advance, but instead is generated at run time Program can generate SQL statements at run time that are required to respond to ad hoc queries Attribute list and the condition are not known until the end user specifies them Tends to be much slower than static SQL Requires more computer resources More likely to be incompatibilities among DBMS vendors Dynamic SQL Example 7 SELECT :W_ATTRIBUTE_LIST FROM :W_TABLE WHERE :W_CONDITION Variables are text variables which are built as the program executes End Procedural SQL 7