Sunteți pe pagina 1din 19

PL/SQL - 1

Define PL/SQL. Explain its purpose Advantages of PL/SQL Main Features of PL/SQL PL/SQL Architecture Basic Structure of PL/SQL Variables and Types Simple PL/SQL Programs Create Pl/SQL block dynamically and then execute it by calling 'DBMS_SQL.EXECUTE' Explain the statement provided by PL/SQL, i.e. Conditional Control Statements, Iterative Statements, Sequential Control Statements SQL vs. PL/SQL Both PL/SQL and Java/.NET code can be used to create Oracle stored procedures and triggers. Which of the one should be used and why? Explain how to see modified code in oracle, i.e. using Oracle Data Dictionary Explain how to keep a history of PL/SQL code changes. Explain the purpose of binary wrapper utility in oracle. How can we protect PL/SQL source code? Explain how to debug PL/SQL program. How can we read and write operating system files from PL/SQL program? How can we call DDL statements like CREATE, DROP, TRUNCATE, etc. from PL/SQL? Show in an example Difference between %TYPE and %ROWTYPE. How can we execute an operating system command from PL/SQL? Example Illustrate how to loop through table in PL/SQL. What is a mutating and constraining table? Difference between stored procedures and functions Define PL/SQL and explain its purpose? PL/SQL is Procedural Language SQL that is an extension of SQL that results in a more structural language composed of blocks. It is mainly used in writing applications that needs to be structured and has error handling. Advantages of PL/SQL Because of the block nature, multiple statements are processed at once thereby improving performance. PL/SQL handles exceptions on catching, which, action can be taken. The block can be stored and reused. PL/SQL is highly portable as it works with all procedural languages and is highly secured because of privileges. Main Features of PL/SQL 1) Offers conditional blocks of code having if else etc. 2) Offers error handling. It can handle exceptions. 3) The blocks can be nested within each other. 4) The PL/SQL engine processes the statements in blocks. The block typically looks like DECLARE BEGIN EXCEPTION END PL/SQL Architecture The architecture consists of PL/SQL block, PL/SQL engine and an oracle server in which the PL/SQL engine is embedded. PL/SQL block of statements are sent to the PL/SQL engine for processing. The PL/SQL engine executes procedural statements but sends SQL statements to the SQL engine in the Oracle database. Basic Structure of PL/SQL - A PL/SQL block consists of:DECLARATIVE section- This is where all variables are declared. BEGIN section- This section contains the PL/SQL block. The statements of code are written in this block. EXCEPTION- Any exceptions that are anticipated are written here.

PL/SQL - 2
Variables and Types Just like in any other language, PL/SQL constants and variables need to be declared before using them in your statements. The variables are declared in the BEGIN section. Variables can take data types as CHAR, DATE, or NUMBER. Example for declaring variables: DECLARE Student_id NUMBER(6); student_name VARCHAR2(20); Simple PL/SQL Programs a) To give 10% hike in current salary from employee table and insert into appraisal table. DECLARE salary NUMBER(8,2); emp_id NUMBER(6) := 100; BEGIN SELECT salary * 0.10 INTO appraisal FROM employees WHERE employee_id = emp_id; END; b) To display employees with id < 100. BEGIN FOR someone IN (SELECT * FROM employees WHERE employee_id < 100 ) LOOP DBMS_OUTPUT.PUT_LINE('First name = ' || someone.first_name || ', Last name = ' || someone.last_name); END LOOP; END; Create Pl/SQL block dynamically and then execute it by calling 'DBMS_SQL.EXECUTE' DBMS_SQL.EXECUTE function is used to execute cursor. It accepts the id of the cursor and returns the number of rows processed. Syntax: DBMS_SQL.EXECUTE ( c IN INTEGER) RETURN INTEGER; Where c is the id of cursor. Explain the statement provided by PL/SQL, i.e. Conditional Control Statements, Iterative Statements, Sequential Control Statements Conditional control statements: they are the typical IF/ELSE statements. IF clause checks a condition, the THEN clause defines what to do if the condition is true and the ELSE clause defines what to do if the condition is false or null. Example: IF sal < 3000 THEN sal_increment := .12; ELSE sal_raise := .09; END IF; Iterative statements: Iterative statements uses loops to execute statements in iterations. The FOR loop for instance, lets you specify a range and then execute the statements. Example: FOR i in 1..100 LOOP SOME STATEMENTS END LOOP; Sequential Control Statements:- GOTO is an example of Sequential control statements. GOTO statement transfers control to the labeled statement. Example: IF total > 25000 THEN GOTO print_total; ELSE GOTO calc_total; SQL vs. PL/SQL

PL/SQL - 3
SQL is a structured query language while PL/SQL is an extension of SQL by introducing a procedural flow. PL/SQL has blocks of statements. PL/SQL works like other procedural languages and has concepts like control statements, sequential statements, exception handling etc. Both PL/SQL and Java/.NET code can be used to create Oracle stored procedures and triggers. Which of the one should be used and why? Even though both PL/SQL and Java/.NET can be used, PL/SQL stands above these two in terms of integration overhead. This is because Java is an open source proprietary and Data manipulation is slightly faster in PL/SQL than in Java. Explain how to see modified code in oracle, i.e. using Oracle Data Dictionary Data dictionary in oracle is a read only set of tables providing information about changed schema objects, default values and lot more. The data dictionary is stored in databases SYSTEM tablespace. We can use SQL statements (select only) to view data of data dictionary. Explain how to keep a history of PL/SQL code changes? Using AFTER CREATE schema trigger, once can keep a history of changes to code. Example: CREATE OR REPLACE TRIGGER change_hist -- Store code in hist table AFTER CREATE ON TEST.SCHEMA -- TEST IS schema name DECLARE BEGIN IF ORA_DICT_OBJ_TYPE in ('PROCEDURE', 'FUNCTION', 'PACKAGE', 'PACKAGE BODY', 'TYPE', 'TYPE BODY') THEN -- Store old code in SOURCE_HIST table INSERT INTO SOURCE_HIST SELECT sysdate, all_source.* FROM ALL_SOURCE WHERE TYPE = ORA_DICT_OBJ_TYPE -- DICTIONARY_OBJ_TYPE IN 8i AND NAME = ORA_DICT_OBJ_NAME; -- DICTIONARY_OBJ_NAME IN 8i END IF; EXCEPTION WHEN OTHERS THEN raise_application_error(-20000, SQLERRM); END; Explain the purpose of binary wrapper utility in oracle. How can we protect PL/SQL source code? PL/SQL code can be protected using the binary wrapper utility. It is located in the ORACLE_HOME/bin directory. Syntax: wrap iname=myscript.pls oname=xxxx.plb There is no way to unwrap the *.pls files and hence must be backed up. Explain how to debug PL/SQL program? One can debug PL/SQL program by printing the output using DBMS_OUTPUT package. Put_line can be used to display a line as shown below: set serveroutput on //displays buffer begin dbms_output.put_line(Sample line'); end; How can we read and write operating system files from PL/SQL program? The UTL_FILE database package can be used to read and write operating system files. You need to have read /write access rights in that directory before the package can be used. Example to write file: Fhandler is a variable of type UTL_FILE.FILE_TYPE UTL_FILE.PUTF(fHandler, 'Im writing to a file\n'); Example to read file: UTL_FILE.GET_LINE(fHandler, buf); How can we call DDL statements like CREATE, DROP, TRUNCATE, etc. from PL/SQL? Show in an example

PL/SQL - 4
EXECUTE IMMEDIATE command can be used to call DDL statements. Example: begin execute Immediate 'TRUNCATE TABLE employee'; end; How can we use dynamic SQL statements from PL/SQL? EXECUTE IMMEDIATE command can be used to call DDL statements. This is available after oracle 8i. Example: EXECUTE IMMEDIATE 'CREATE TABLE employee (id NUMBER)'; What is the Difference between %TYPE and %ROWTYPE? %type is used to declare a field of a table while %rowtype is used to declare a record with the same type as specified in that table, view or cursor. Example of %type: DECLARE v_EmployeeName emp.ename%TYPE Example of %rowtype DECLARE v_empployee emp%ROWTYPE; How can we execute an operating system command from PL/SQL? Example There is no direct way to execute an OS command from PL/SQL. Indirect methods like database pipes, external procedure listeners can be used. The commands can be executed within the pipe and the listener picks it up and run the requests. Results are passed back on a different database pipe. Illustrate how to loop through table in PL/SQL? Cursors can be used to loop through tables in PL/SQL. Example: Employee cursor all employees for subject. CURSOR emp_cur (v_sub_no subject.subjectno%TYPE) IS SELECT employeename FROM emp WHERE subjectno = v_ subjectno; What is a mutating and constraining table? A mutating table is a table that is being modified by an INSERT, UPDATE or DELETE statement. When any such table is targeted by a trigger, oracle throws an error because it is under a mutated state. Such error also occurs if a trigger attempts to change the primary, foreign or unique key columns of the table. Such tables are constraining tables. What are the differences between stored procedures and functions? Stored procedures dont return any value while functions return values. Stored procedures are mainly used to process a task while functions are used to calculate. Functions can be called from procedures while the other way is not possible.

PL/SQL control structures


Conditional control: IF and CASE Statements. Sequential Control: GOTO and NULL Statements. Explain with an example for each IF statement- It is a conditional statement in which if the condition is true, the statement is processed. Example: IF sal > 10000 THEN compute_bonus(empid); UPDATE salary SET appraisal = appraisal + bonus WHERE empno = emp_id; END IF; CASE statement- It is again a conditional statement that executes the statement if the condition in CASE is true. IF salary = '1000' THEN dbms_output.put_line('LOW SALARY');

PL/SQL - 5
ELSIF grade = '2000' THEN dbms_output.put_line('HIGH SALARY); END IF; Iterative Control: LOOP and EXIT Statements LOOP:- Loop executes a statement multiple times in loop. EXIT loop forces the LOOP to exit forcibly. Example: LOOP IF university_rating < 3 THEN ... EXIT; -- exit loop immediately END IF; END LOOP; Sequential Control: GOTO and NULL Statements; Explain with an example for each GOTO statement takes the control to the labeled statement. Example: BEGIN ... GOTO label1; ... <<label1>> INSERT INTO emp VALUES ... END; NULL statement- Simply passes the control to the next statement. Example: IF salary < 9000 THEN compute_appraisal(emp_id); ELSE NULL; END IF; What is SQL*Loader? SQL*Loader is a loader utility used for moving data from external files into the Oracle database in bulk. It is used for high performance data loads. It is available as part of the free Oracle 10g Expression Edition. Features: Capability of loading data from multiple data files into multiple tables in a single session. Specification of the character set of data. Sophisticated error report generation. Capabilities of loading data directly to Oracle datafiles using the normal insert process. SQL loader uses following files Method for loading data Connectional path load Direct Path load What is a SQL*Loader Control File? A SQL*Loader control file contains the following specification: Location of the input data file The format of the input date file The target table where the data should be loaded The way input data fields should be mapped to target table columns. Select criteria to select input records for loading. Location where the errors should be reported. What are the original Export and Import Utilities?

PL/SQL - 6
The import and export utilities of oracle provide a very simple way to transfer data objects between Oracle databases. These may reside on heterogeneous software and hardware platforms. The exported data objects are extracted and written to an export dump file. The Import utility reads the object definitions and table data from the dump file. An export file is an Oracle binary-format dump file located on disk or tape which can be transferred by using FTP or physically transported. They can then be used with the Import utility to transfer data between databases on a single system. The files can also be used as backups in addition to normal backup procedures. Export and Import utilities are now being replaced by Data Pump Export and Import utilities in Oracle 10g. What are the use of Export and Import command? Import and export in Oracle is used to move logical objects like tables in and out of the database. Example: Export entire database in db..dmp file:exp SYSTEM/password FULL=y FILE=dba.dmp LOG=dba.log CONSISTENT=y FULL specifies the entire database to be dumped. What are the parameters to be provided while executing Export and Import commands? The parameters that need to be provided while executing IMPORT or EXPORT commands are: The file name Write access The commit count number The nickname For example: IMPORT FROM file_1.ixf OF IXF ALLOW WRITE ACCESS COMMITCOUNT 20 INSERT INTO NICKNAME_1; What is the difference between the SQL*Loader and IMPORT utilities? SQL*Loader is a high speed data loading mechanism. It can load data from external files into tables of the database. IMPORT does not support any direct options while SQL*Loader does. Import has more tuning limitations. IMPORT mainly used for reading and writing the operating system files. SQL*Loader can be used to load data from Delimiter separated files and fixed or variable width text. On the other hand, the import utility read files that are generated by other export utility of oracle. What are the purposes of Import and Export utilities? Export and Import are the utilities provided by oracle in order to write data in a binary format from the db to OS files and to read them back. These utilities are used: To take backup/dump of data in OS files Restore the data from the binary files back to the database. Move data from one owner to another Import and Export utilities are helpful in following ways: They can be used for backup and recovery process. They can also be used while moving database between two different oracle instances. These utilities can be used to move data from one tablespace to other.

PL/SQL collections
What is a Collection? A collection just like an array is an ordered group of elements of the same type. Each elements position is determined by a unique subscript. Explain collection types. i.e. Index-by tables, Nested tables, Varrays. Simple example for each

PL/SQL - 7
Index by tables:- They are similar to hash arrays that allows to search for subscript values using arbitrary numbers and strings. They can be declared as: TYPE type_name IS TABLE OF element_type [NOT NULL] INDEX BY [BINARY_INTEGER | PLS_INTEGER | VARCHAR2(size_limit)]; INDEX BY key_type; Example: TYPE studenttyp IS TABLE OF emp%ROWTYPE INDEX BY BINARY_INTEGER; stud_tab studenttyp; Nested tables:- they hold random number of elements and use sequential numbers as sub scripts. They can be declared as: TYPE type_name IS TABLE OF element_type [NOT NULL]; Example: TYPE employee_type IS TABLE OF NUMBER INDEX BY VARCHAR2(64); Varrays: Holds a fixed number of elements which can be changed in run time. They can be declared as: TYPE type_name IS {VARRAY | VARYING ARRAY} (size_limit) OF element_type [NOT NULL]; Example: TYPE Calendar IS VARRAY(366) OF DATE; Nested Tables vs. Associative Arrays Arrays have an upper bound while nested tables dont have a bound. Arrays must have consecutive subscripts while nested tables can have both consecutive and non consecutive scripts. Nested Tables vs. Varrays Nested tables hold random number of elements while varrays holds fix number of elements. Each varray is stored as a single object while Nested table data is stored out-of-line in a store table. Explain the methods exist for collections: - EXISTS , COUNT , LIMIT , FIRST and LAST , PRIOR and NEXT , EXTEND, TRIM , DELETE EXISTS:- if nth element is present in a collection, it returns true. Example: IF subject.EXISTS(i) THEN subject(i) := new_subject; END IF; COUNT:- counts the number of elements in a collection. Example: IF subjects.COUNT = 25 THEN ... LIMIT:-Used in varrays, LIMIT returns the bound value or maximum number of elements the varray can contain. Example: IF subjects.LIMIT = 25 THEN ... FIRST:- Returns the first member of the collection. Example: IF subject.FIRST = subject.LAST THEN ... LAST:- Returns the last member of the collection. Example: IF subject.FIRST = subject.LAST THEN ... PRIOR:-Returns the preceding index number of nth element. Example: n := subjects.PRIOR(subjects.FIRST); PRIOR:-Returns the next or succeeding index number of nth element. Example: i := subjects.NEXT(i); EXTEND:- Used to increase the size of nested table or varray. It either appends one null element to a collection, n null elements or n copies of ith element of a collection. Example: subjects.EXTEND(5,1); //appends 5 copies of element 1. TRIM:- Used to decrease the size of collection by removing one element from end of collection or n elements. Example: subjects.TRIM(3); DELETE:- Deletes the collection elements. It either deletes all elements, nth element from an array, all elements in the range m, n. Example: subjects.DELETE(2);

PL/SQL record data type


What is a PL/SQL Record data type?

PL/SQL - 8
A record data type represents a data type for that row in a database table. It lets u define your own records and not your own fields. Define and declare Records A record has its own name and type that stores group of related data items. %ROWTYPE helps you declare a rowtype. Example: TYPE employeeRec IS RECORD ( emp_id emp.empno%TYPE, emp_name VARCHAR2(14), emp_loc VARCHAR2(13)); Different Types of Records - Table-based, Cursor-based, Programmer-defined Table based records:- Such records are based on tables. This means that the structure of the records is based on structure of the tables. The record field corresponds to a column of the table. Example: Table structure: CREATE TABLE salary (employee_code NUMBER (5), Employee_sal NUMBER ); Lets say, record for the above table were named salary_rec, then the fields would each be referred to as: salary_rec.employee_code salary_rec.employee_sal cursor based:- Such records are based on select list of a cursor. Each field in record is connected to some column in the cursor query. Example: <record_name> <cursor_name>%ROWTYPE; Programmer defined:- These are defined by programmer and have got nothing to do with cursors or tables. In order to define it, first, a record TYPE containing the structure needs to be created and then this record type can be used in actual records having that structure. Example: TYPE <type_name> IS RECORD (<field_name1> <datatype1>, ) Benefits of using Records They help you treat data as logical units. This makes it easier to organize and represent information. Guidelines for using Records a) Nested record types are not supported b) ROW cannot be used with a subquery. c) Record variables are not allowed in select, where or group by clause d) The keyword ROW is allowed only on the left side of a SET clause Rules you must follow for referencing a record in its entirety or a particular field in the record Fields in a record are accessed by name. Example: emp_info.joining_date ... You must always use the fully qualified name of a field when referencing that field. There is no need to use dot notation when you reference the record as a whole; you simply provide the name of the record.

PL/SQL cursors
What are Cursors? Cursors help you manipulate the information retrieved by select statements. This can be done by assigning a name to the cursor.

PL/SQL - 9
Example: CURSOR emp_cur IS SELECT emp_number from employee_tbl where employee_name = name_in; Types of cursors in PL/SQL - Implicit cursors, Explicit cursors Implicit cursors- These cursors are not declared by the programmer. They are issued when the SQL statement is executed. The open, close and fetching is done by itself. Example: UPDATE employee SET salary = salary * 2.1; Here, an implicit cursor is issued to identify the set of rows in the table which would be affected by the update. Explicit cursors- These cursors are defined by programmer. They are used in queries that return multiple rows. Example: CURSOR emp_cur IS SELECT emp_number from employee_tbl where employee_name = name_in; Define cursor attributes: %FOUND, %NOTFOUND, %ROWCOUNT, and %ISOPEN %FOUND- This is a Boolean variable which evaluates to TRUE if the last row is successfully fetched. %NOTFOUND- This is a Boolean variable which evaluates to TRUE if the last row is not successfully fetched. This means there are no more rows to fetch. %ROWCOUNT- Returns the number of rows fetched by the cursor. %ISOPEN- If the cursor is open, it evaluates to TRUE else FALSE. What are cursor variables? Explain with an example Cursor variables are references to the query set or the rows. They help you traverse the rows and most importantly, they help you pass results from one PL/SDQL program to another. Example: DECLARE /* Create the cursor type. */ TYPE employee_curtype IS REF CURSOR RETURN employee %ROWTYPE; /* Declare a cursor variable of that type. */ employee_curvar employee_curtype; Significance of SELECT FOR UPDATE clause: Write syntax SELECT FOR UPDATE statement selects the rows in the cursor result set in order to lock them. The lock is released in the next commit or rollback statement. Syntax: CURSOR cursor_name IS select_statement FOR UPDATE [of column_list] [NOWAIT]; Significance of WHERE CURRENT OF clause: Write syntax WHERE CURRENT OF clause enables you to update or delete last fetched record by the cursor. These records are referenced by the SELECT FOR UPDATE clause. Syntax: UPDATE table_name SET set_clause WHERE CURRENT OF cursor_name; Why do we use cursor variables? Cursor variables allow you to pass them as arguments to a function which in turn enables you to share results. They allow you to assign contents of one cursor to another variable. Using a single cursor variable you can fetch from different result sets. What are the restrictions on cursor variables? a) Because cursor variables have no persistent state, they cannot be declared in a package. b) RPCs cannot be used to pass cursor variables. c) NULL values cannot be assigned to cursor variables d) They cannot be used by dynamic SQL. e) They cannot be used with operators for equality etc.

PL/SQL - 10
PL/SQL error handling
Overview of PL/SQL Error Handling When the system throws a warning or has an error it can lead to an exception. Such exception needs to be handled and can be defined internally or user defined. Exceptions stop normal execution. Internal exceptions are the ones handled by system like divide by zero, out of memory etc. Advantages of PL/SQL Exceptions They improve readability of the code by separating the error routines in the code. Exceptions help you handle errors. Each and every point of error need not be checked as exception handler can be added to the PL/SQL block. Explain some of the commonly used Predefined PL/SQL Exceptions 1) Divide by zero This is raised when any number is attempted to divide by zero. 2) TOO MANY ROWS- A SELECT INTO statement returns more than one row 3) CASE_NOT_FOUND- No choice in the WHEN clause of a case statement is selected. 4) LOGIN_DENIED- An attempt to login with an invalid username or password 5) PROGRAM_ERROR- An internal PL/SQL problem What is user-defined exception? Explain it with an example. A user-defined exception is what the programmer defines depending on the needs. These exceptions need to be explicitly raised. Example: DECLARE salary_due EXCEPTION; They can be raised by giving the command RAISE salary_due. Explain how PL/SQL exceptions are raised? PL/SQL exceptions are raised using the RAISE command. This command is used when exceptions are defined by programmer and not implicit exceptions. Example: Declare and raising an exception: DECLARE short_of_attendance EXCEPTION; min_attendance NUMBER(4); BEGIN ... IF min_attendance < 10 THEN RAISE short_of_attendance; END IF; EXCEPTION WHEN short_of_attendance THEN -- handle the error END; Illustrate reraising a PL/SQL Exception? Reraising an exception is possible by handling it locally Example: DECLARE out_of_attendance EXCEPTION; BEGIN ... BEGIN ---------- sub-block begins ... IF ... THEN RAISE out_of_attendance; -- raise the exception END IF; EXCEPTION WHEN out_of_attendance THEN -- handle the error RAISE; -- reraise the current exception

PL/SQL - 11
END; ------------ sub-block ends EXCEPTION WHEN out_of_attendance THEN -- handle the error differently ... END; Demostrate how to handle raised PL/SQL exceptions? Raised exceptions are caught using exception handlers that help handling the exceptions to let the system know what suitable action needs to be taken. Example: When the exception is raised, sequence of statements let the system know what action needs to be taken. EXCEPTION WHEN exception_name1 THEN -- handler sequence_of_statements1 WHEN exception_name2 THEN -- another handler sequence_of_statements2. Tips for handling PL/SQL errors 1) When an exception is raised it should be handled well so that system does not collapse. 2) When an exception is raised, retry the transaction rather than abandoning it. 3) Make use of locator variables to track statement executions.

PL/SQL subprograms
What are PL/SQL Subprograms? What are the parts of PL/SQL Subprograms? Explain with an example Advantages of PL/SQL Subprograms. PL/SQL has two types of subprograms called procedures and functions. Explain them. How does subprogram pass information? What are actual and formal subprogram parameters? Explain with an example Define three parameter modes, IN (the default), OUT, and IN OUT that can be used with any subprogram. Depicts example for default values for subprogram parameters. Overview of Table Functions with an example. What are Pipelined Table Functions? Explain how to implement it. What is a Recursive Subprogram? Explain with an example of this kind. Explain how to call external subprograms from any PL/SQL block. What is PL/SQL server page? Explain its working. What are PL/SQL Subprograms? Named PL/SQL blocks of code which can be invoked using parameters are called PL/SQL sub programs. What are the parts of PL/SQL Subprograms? Explain with an example A PL/SQL program has 3 basic parts Declaration Block Executable Block Exception Block Ex: DECLARE annual_salary NUMBER (8,2) BEGIN Select base*12 into annual_salary from employee where employee_id=6; EXCEPTION WHEN NO_DATA_FOUND THEN dbms_output.put_line('There is no data for this employee'); END; Advantages of PL/SQL Subprograms

PL/SQL - 12
The application makes a single call to the database to run a block of statements which improves performance against running SQL multiple times. This will reduce the number of calls between the database and the application. PL/SQL is secure since the code resides inside the database thus hiding internal database details from the application. The application will only make a call to the PL/SQL sub program PL/SQL and SQL go hand in hand so there would be no need of any translation required between PL/SQL and SQL. PL/SQL has two types of subprograms called procedures and functions. Explain them. Procedures: A procedure is a reusable, named block of code which accepts parameters and may or may not return any value after completion of execution. Three types of parameters can be used in a Procedure: A. IN parameter B. OUT parameter C. IN/OUT parameter Since a procedure is sub program it has a DECLARATION, EXECUTABLE and EXCEPTION blocks. Syntax: CREATE OR REPLACE PROCEDURE SAMPLE//this statement creates a new //procedure or replace is one //already exists with the same name IS ( emp_id IN OUT integer dept_id IN integer annual_sal OUT integer ) AS BEGIN select employee_id , base_pay*12 into emp_id , annual_sal from employee where employee_id=emp_id and department_id=dept_id; END; Functions : A function is also a subprogram which computes and returns a value. The function can also be used as part of an Sql. Statement. Ex: CREATE OR REPLACE FUNCTION EmpName (emp_id in integer ) return varchar2 IS employee_name varchar2(100); BEGIN select emp_name into employee_name from employee where emp_id=emp_id; RETURN employee_name; EXCEPTION WHEN NO_DATA_FOUND employee_name='NA'; END; A function will always return a value. A procedure may or may not return a value. The return statement in a function returns the results of the function to the calling program. A procedure only returns control to the calling program Functions can be called in SQL statement(s). Procedures cannot be called in SQL statement(s). How does subprogram pass information? What are actual and formal subprogram parameters? Explain with an example Sub programs pass information using parameters. There a two types of parameters actual parameters and formal parameters. Formal parameters are parameters that are used in the sub program definition. Actual parameters are the actual values passed to the formal parameters when the sub program is called. Ex:

PL/SQL - 13
CREATE OR REPLACE FUNCTION Employee (emp_id IN integer , grp_id IN integer ) //formal parameters return integer AS base integer; BEGIN select base_salary to base from employee where employee_id=emp_id and department_id = dept_id; RETURN base ; EXCEPTION WHEN NO_DATA_FOUND base=0; END; Employee(12345 , 67); //actual parameters are values passed to the function Define three parameter modes, IN (the default), OUT, and IN OUT that can be used with any subprogram. An IN parameter is used to send input values to the sub program. The IN parameters values cannot be changed You can assign value either using the := operator or the DEFAULT key word. An OUT parameter is the value returned to the calling program.The value is initially set as NULL. An I N OUT parameter can be used as an input and an output parameter.It can be assigned a default value like an IN parameter.Any changes made to the parameter during the execution of the sub program is returned as the OUT parameter value. Ex: ( parameter_1 IN VARCHAR2 := 'ABC', parameter_2 IN VARCHAR2 DEFAULT 'ABC', parameter_3 OUT number, parameter_4 IN OUT number DEFAULT '1' ) Depicts example for default values for subprogram parameters? Ex: CREATE OR REPLACE PROCEDURE sample ( name IN varchar2 :='SAMPLE', address IN varchar2, emp_id OUT integer , emp_date IN OUT date ) AS BEGIN END; Overview of Table Functions with an example Table functions are functions that return a collection of rows. They can be used as a table , view or also a part of the query. The input can be a collection or an cursor. Ex: CREATE TYPE person as OBJECT // create a declaration of the object ( name as varchar2(100), address as varchar2 (200), ); CREATE TYPE person_array as a TABLE of person; // create a table of the object declared What are Pipelined Table Functions? Explain how to implement it. Pipelined table functions let us fetch results as they are processed and not wait for a complete execution. This improves performance and usage of memory resources. Ex:

PL/SQL - 14
CREATE TYPE numb_array as table of number; CREATE FUNCTION num_func(numb IN number) RETURN numb_array PIPELINED AS BEGIN FOR I IN 1..100 PIPE ROW(I); END LOOP; RETURN; END; Pipeline functions are used when a data source is required which is not a table used in the select statement. What is a Recursive Subprogram? Explain with an example of this kind. A recursive subprogram is a subprogram that calls itself. Each call creates a new instance of the subprogram. Ex: Finding factorial of a given integer FUNCTION factorial(input_n INTEGER) RETURN integer IS BEGIN IF input_n=1 THEN RETURN 1; ELSE RETURN input_n * factorial(input_n-1); END IF; END factorial; Explain how to call external subprograms from any PL/SQL block. First you will have write a Java class and then create a Procedure to call the PL/SQL block CREATE OR REPLACE AND RESOLVE JAVA SOURCE HelloWorld AS public Class HNClass () { public static void HNFunc(String arg) { System.out.println(Hello World+arg); } } CREATE OR REPLACE PROCEDURE call_java IS PROCEDURE execute() AS LANGUAGE JAVA NAME 'HNClass.HNFunc(java.lang.String)'; END; What is PL/SQL server page? Explain its working. PL SQL server page are database procedures that run on the database server to produce dynamic content in Web applications. <%@ plsql procedure="show_items_available " %> <HTML> <HEAD><TITLE>Show Items Available </TITLE></HEAD> <BODY> <UL> <% FOR item IN (SELECT product_name, list_price FROM item_sale ORDER BY list_price DESC) LOOP %> <LI> Item = <%= item.product_name %><BR> Price = <% = item.list_price %><BR> <% END LOOP; %>

PL/SQL - 15
</UL> </BODY> </HTML>

PL/SQL packages
What is a PL/SQL package? Advantages of PL/SQL Packages What are the types and layers of Packages? Explain them PL/SQL Packages features Guidelines for writing packages What is a PL/SQL package? A package is a collection of related PL/SQL objects. The package contains a body and a specification. The package specification has the declaration which is public and can be used in the PL/SQL sub programs inside the package. The package body holds the implementation of all the PL/SQL objects declared in the specification. Example of a PL/SQL Package. CREATE OR REPLACE PACKAGE emp_data AS PROCEDURE add_employee ( ename VARCHAR2, job VARCHAR2, mgr NUMBER, sal NUMBER, deptno NUMBER); END emp_actions; CREATE OR REPLACE PACKAGE BODY emp_data AS PROCEDURE add_employee ( ename VARCHAR2, job VARCHAR2, mgr NUMBER, sal NUMBER, deptno NUMBER) IS BEGIN INSERT INTO emp VALUES (empno_seq.NEXTVAL, ename, job, mgr, SYSDATE, comm, deptno); END add_employee; END emp_data; Advantages of PL/SQL Packages Packages are easier for application designing, encapsulating data, additional functionality and better performance. An application has various modules which can be placed in packages and handled easier. What are the types and layers of Packages? Explain them The different types of packages are Built in , Pre-build and new packages build new based on requirements. The following are the layers of PL/SQL from the bottom up approach SQL language layer is the lowest layer of the package. A PL/SQL standard package is the next layer of the package. Pre-built code and library packages. PL/SQL Packages features The PL/SQL packages allow you to declare Types, Cursors, exceptions, functions and procedures. All the initialization can be done in the package Specification and variables are initialized once.

PL/SQL - 16
Private vs. Public items in Packages. The objects declared in the package specification are visible outside the package. The objects declared in the body of the implementation of the objects those are private variables. Guidelines for writing packages 1. Packages need to be grouped with general PL/SQL subprograms so it can be reused in the entire application. 2. Package specifications are not mandatory but its always a good practice to have them declared. 3. Do not write more than 10,000 lines of code in package body. This may decrease the performance when a program is called from the package. 4. Changes in package specifications need a recompiling of all the supported objects. But that is not required when changes are done to the body of the package. So keep changes to the specification at the least.

PL/SQL triggers
What is a Trigger? Syntax of Triggers Types of PL/SQL Triggers How to obtain information about any trigger? What is CYCLIC CASCADING in a TRIGGER? What is a Trigger? Syntax of Triggers Triggers are procedures that are stored in the database and are implicitly run, or fired, when something happens. Traditionally, triggers supported the execution of a PL/SQL block when an INSERT, UPDATE, or DELETE occurred on a table or view. Triggers support system and other data events on DATABASE and SCHEMA. Syntax: CREATE OR REPLACE TRIGGER [Trigger Name] [Before / After / Instead Of] ON [schema].[table] <pl/sql subprogram>

What is trigger in oracle?


Triggers are constructs in PL/SQL that need to be just created and associated with a table. Once they are created, when the table associated with it gets updated due to an UPDATE, INSERT or a DELETE, the triggers get implicitly fired depending upon the instructions passed to them

Types of PL/SQL Triggers Row trigger - The trigger fires for each ROW affected. Statement trigger The trigger is fired once when the condition is matched Before and After trigger The BEFORE trigger run the trigger action before the insert, update or delete statement. The AFTER trigger runs the trigger action after the insert, update or delete statement is executes. PL/SQL triggers execution hierarchy The statement level triggers are executed and then row level triggers executed. First all BEFORE statements that apply. During which Integrity constraint is performed. Run all AFTER statements that apply. During which Integrity constraint is performed. SQL statement is executed. How to obtain information about any trigger? A select statement against the USER_TRIGGERS table will provide the information of the triggers. What is CYCLIC CASCADING in a TRIGGER?

PL/SQL - 17
When one or more trigger enters into an infinite loop the triggers can enter into cyclic cascading. Lets say Trigger A is inserting a row into table employee and update department Trigger B is inserting a row into table department and insert into table employee This is a cyclic situation which may lead to the crashing of the database.

What are triggering attributes?


Triggers can be fired based on the following criteria: Category - (INSERT, DELETE, UPDATE) i.e. which kind of DML statement causes the trigger to fire. Timing (BEFORE or AFTER) i.e. whether the trigger fires before the statement is executed of after. Level (Row or Statement) i.e. whether it fires once for each row affected by trigger statement or whether it fires once.

What are cascading triggers?


At times when SQL statement of a trigger can fire other triggers. This results in cascading triggers. Oracle allows around 32 cascading triggers. Cascading triggers can cause result in abnormal behavior of the application.

OR
A Trigger that contains statements which cause invoking of other Triggers are known as cascading triggers. Heres the order of execution of statements in case of cascading triggers: Execute all BEFORE statement triggers that apply to the current statement.

OR

Loop for each row affected statement. Execute all BEFORE row triggers that apply to the current statement in the loop. Lock and change row, perform integrity constraints check; release lock. Execute all AFTER row triggers that apply to the current statement. Execute all AFTER statement triggers that apply to the current statement.

When a statement in a trigger body causes another trigger to be fired, the triggers are said to be cascading.

What are the types of triggers available in Oracle Reports?


Types of triggers in Oracle reports: 1 before parameter form 2 after parameter form 3 before report 4 between pages 5 after report

PL/SQL sequences Define PL/SQL sequences and write syntax for a sequence What does cache and no cache options mean while creating a sequence? How do we set the LASTVALUE value in an Oracle Sequence? How does one get the value of a sequence into a PL/SQL variable? Define PL/SQL sequences and write syntax for a sequence A sequence is a database object that is used to generate sequential number. CREATE SEQUENCE seqname [increment] [minimum value][maximum value][start][cache][cycle] Nextval and currval lets us get the next value and current value from the sequence. What does cache and no cache options mean while creating a sequence? The CACHE option means how many sequences will be stored in memory for access by the application objects. The performance is faster. However in case of the database is down the data is memory is lost for the sequence. The NO CACHE option means values are not stored in memory. So there might be some performance issue. How do we set the LASTVALUE value in an Oracle Sequence? ALTER SEQUENCE emp_id INCREMENT by 7000 How does one get the value of a sequence into a PL/SQL variable? CREATE SEQUENCE emp_seq ; SELECT emp_seq.NEXTVAL into lv_variable from dual; Oracle/PLSQL indexes What is an Index? Explain how to create an Index. What is Function-Based Index? Create a Function-Based Index

PL/SQL - 18
What is an Index? Explain how to create an Index. An index is a object which is used to improve performance during retrieval of records. CREATE [UNIQUE] INDEX index_name ON employee[emp_id, emp_name,dept_id] [COMPUTE STATISTICS] The UNIQUE keyword is used when combined values of the index should be unique. The COMPUTE STATISTICS during the creation of index optimizes the plan of execution of the SQL statement and improves performance. What is Function-Based Index? Create a Function-Based Index Instead of adding a index to a column, you index the function on that column. CREATE INDEX sample_index on employee (UPPER(employee_name)); SELECT * FROM employee WHERE Upper(employee_name)='BILL'; What are the guidelines to decide which column to index? Non-key columns can be dropped from a table only after the non-key index is dropped first. Columns cant be defined in both the key column and the INCLUDE list. Non-key columns can be included only in non-clustered indexes. Column names cant be repeated in the INCLUDE list. For Included Column Index to exist there must be at least one key column defined with a maximum of 16 key columns and 1023 included columns. What is composite index? A composite index is comprised of two or more columns. Composite indexes should be avoided as they are large in size and can be have a performance overhead. Example: Create a composite index with columns name and id. CREATE NONCLUSTERED INDEX student_id ON student (ID, name) Oracle - What is composite index? - August 28, 2008 at 15:00 PM by Amit Satpute What is composite index? A composite index contains more than one key column. Composite indexes can provide additional advantages over single column indexes. What is INDEX_BY_BINARY_INTEGER? BINARY_INTEGER is an indexing data type for associative arrays that is a subtype if INETGER. Values that can be taken up by this data type range from -2,147,483,647 to 2,147,483,647. Example: TYPE my_array_t IS TABLE OF VARCHAR2(100) INDEX BY BINARY_INTEGER OR BINARY_INTEGER is a PL/SQL data type defined as a subtype of INTEGER in the STANDARD package and is used for storing signed integers. It can take values between -2,147,483,647 and 2,147,483,647 What is index and explain its purpose? An index typically used to retrieve records of a table at a faster rate. This is because an index contains value of the indexed column. Example: The example below creates an index student_idx in table student for column student_name CREATE INDEX student_idx ON student (student_name); OR An index is a pointer to a location of data. The purpose of an index is to make SQL queries run faster. If the optimizer detects an index that matches part of the WHERE clause of the query, then it uses the index to avoid having to read every row in the table. What are the guidelines to decide which table s to index? On rebuilding an Index, the existing index is dropped and a new one is built. This operation can consume a lot of time and resources.

PL/SQL - 19
When an index is reorganized, the leaf level pages of the index are defragmented to match the logical order by physically reordering them. As rebuilding indexes is an expensive operation, following general guidelines should be taken into consideration: Reorganise an index when the degree of fragmentation is between 5 and 30% Rebuild an index when the degree of fragmentation is over 30%

S-ar putea să vă placă și