PL/SQL – Questions and Answers

PL/SQL Questions and Answers ”; Previous Next PL/SQL Questions and Answers has been designed with a special intention of helping students and professionals preparing for various Certification Exams and Job Interviews. This section provides a useful collection of sample Interview Questions and Multiple Choice Questions (MCQs) and their answers with appropriate explanations. SN Question/Answers Type 1 PL/SQL Interview Questions This section provides a huge collection of PL/SQL Interview Questions with their answers hidden in a box to challenge you to have a go at them before discovering the correct answer. 2 PL/SQL Online Quiz This section provides a great collection of PL/SQL Multiple Choice Questions (MCQs) on a single page along with their correct answers and explanation. If you select the right option, it turns green; else red. 3 PL/SQL Online Test If you are preparing to appear for a Java and PL/SQL related certification exam, then this section is a must for you. This section simulates a real online test along with a given timer which challenges you to complete the test within a given time-frame. Finally you can check your overall test score and how you fared among millions of other candidates who attended this online test. 4 PL/SQL Mock Test This section provides various mock tests that you can download at your local machine and solve offline. Every mock test is supplied with a mock test key to let you verify the final score and grade yourself. Print Page Previous Next Advertisements ”;

PL/SQL – Discussion

Discuss PL/SQL ”; Previous Next PL/SQL is a combination of SQL along with the procedural features of programming languages. It was developed by Oracle Corporation in the early 90”s to enhance the capabilities of SQL. PL/SQL is one of three key programming languages embedded in the Oracle Database, along with SQL itself and Java. This tutorial will give you great understanding on PL/SQL to proceed with Oracle database and other advanced RDBMS concepts. Print Page Previous Next Advertisements ”;

PL/SQL – Quick Guide

PL/SQL – Quick Guide ”; Previous Next PL/SQL – Overview The PL/SQL programming language was developed by Oracle Corporation in the late 1980s as procedural extension language for SQL and the Oracle relational database. Following are certain notable facts about PL/SQL − PL/SQL is a completely portable, high-performance transaction-processing language. PL/SQL provides a built-in, interpreted and OS independent programming environment. PL/SQL can also directly be called from the command-line SQL*Plus interface. Direct call can also be made from external programming language calls to database. PL/SQL”s general syntax is based on that of ADA and Pascal programming language. Apart from Oracle, PL/SQL is available in TimesTen in-memory database and IBM DB2. Features of PL/SQL PL/SQL has the following features − PL/SQL is tightly integrated with SQL. It offers extensive error checking. It offers numerous data types. It offers a variety of programming structures. It supports structured programming through functions and procedures. It supports object-oriented programming. It supports the development of web applications and server pages. Advantages of PL/SQL PL/SQL has the following advantages − SQL is the standard database language and PL/SQL is strongly integrated with SQL. PL/SQL supports both static and dynamic SQL. Static SQL supports DML operations and transaction control from PL/SQL block. In Dynamic SQL, SQL allows embedding DDL statements in PL/SQL blocks. PL/SQL allows sending an entire block of statements to the database at one time. This reduces network traffic and provides high performance for the applications. PL/SQL gives high productivity to programmers as it can query, transform, and update data in a database. PL/SQL saves time on design and debugging by strong features, such as exception handling, encapsulation, data hiding, and object-oriented data types. Applications written in PL/SQL are fully portable. PL/SQL provides high security level. PL/SQL provides access to predefined SQL packages. PL/SQL provides support for Object-Oriented Programming. PL/SQL provides support for developing Web Applications and Server Pages. PL/SQL – Environment Setup In this chapter, we will discuss the Environment Setup of PL/SQL. PL/SQL is not a standalone programming language; it is a tool within the Oracle programming environment. SQL* Plus is an interactive tool that allows you to type SQL and PL/SQL statements at the command prompt. These commands are then sent to the database for processing. Once the statements are processed, the results are sent back and displayed on screen. To run PL/SQL programs, you should have the Oracle RDBMS Server installed in your machine. This will take care of the execution of the SQL commands. The most recent version of Oracle RDBMS is 11g. You can download a trial version of Oracle 11g from the following link − Download Oracle 11g Express Edition You will have to download either the 32-bit or the 64-bit version of the installation as per your operating system. Usually there are two files. We have downloaded the 64-bit version. You will also use similar steps on your operating system, does not matter if it is Linux or Solaris. win64_11gR2_database_1of2.zip win64_11gR2_database_2of2.zip After downloading the above two files, you will need to unzip them in a single directory database and under that you will find the following sub-directories − Step 1 Let us now launch the Oracle Database Installer using the setup file. Following is the first screen. You can provide your email ID and check the checkbox as shown in the following screenshot. Click the Next button. Step 2 You will be directed to the following screen; uncheck the checkbox and click the Continue button to proceed. Step 3 Just select the first option Create and Configure Database using the radio button and click the Next button to proceed. Step 4 We assume you are installing Oracle for the basic purpose of learning and that you are installing it on your PC or Laptop. Thus, select the Desktop Class option and click the Next button to proceed. Step 5 Provide a location, where you will install the Oracle Server. Just modify the Oracle Base and the other locations will set automatically. You will also have to provide a password; this will be used by the system DBA. Once you provide the required information, click the Next button to proceed. Step 6 Again, click the Next button to proceed. Step 7 Click the Finish button to proceed; this will start the actual server installation. Step 8 This will take a few moments, until Oracle starts performing the required configuration. Step 9 Here, Oracle installation will copy the required configuration files. This should take a moment − Step 10 Once the database files are copied, you will have the following dialogue box. Just click the OK button and come out. Step 11 Upon installation, you will have the following final window. Final Step It is now time to verify your installation. At the command prompt, use the following command if you are using Windows − sqlplus “/ as sysdba” You should have the SQL prompt where you will write your PL/SQL commands and scripts − Text Editor Running large programs from the command prompt may land you in inadvertently losing some of the work. It is always recommended to use the command files. To use the command files − Type your code in a text editor, like Notepad, Notepad+, or EditPlus, etc. Save the file with the .sql extension in the home directory. Launch the SQL*Plus command prompt from the directory where you created your PL/SQL file. Type @file_name at the SQL*Plus command prompt to execute your program. If you are not using a file to execute the PL/SQL scripts, then simply copy your PL/SQL code and right-click on the black window that displays the SQL prompt; use the paste option to paste the complete code at the command prompt. Finally, just press Enter to execute the code, if it is not already executed. PL/SQL – Basic Syntax In this chapter, we will discuss the Basic Syntax of PL/SQL which is a block-structured language; this means that the PL/SQL programs are divided and written in logical

PL/SQL – Useful Resources

PL/SQL – Useful Resources ”; Previous Next The following resources contain additional information on PL/SQL. Please use them to get more in-depth knowledge on this topic. Useful Links on PL/SQL Oracle PL/SQL − Oracle”s official website giving complete detail about PL/SQL. PL/SQL on Wikipedia − From Wikipedia, the free encyclopedia of PL/SQL. SQL Tutorial − A simple tutorial SQL which is one of the most important DML used in PL/SQL. MySQL Tutorial − A simple tutorial on MySQL which is an alternate of Oracle Database. Java tutorial − Learn JAVA which is making use of PL/SQL stored procedures. Useful Books on PL/SQL To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;

PL/SQL – Date & Time

PL/SQL – Date & Time ”; Previous Next In this chapter, we will discuss the Date and Time in PL/SQL. There are two classes of date and time related data types in PL/SQL − Datetime data types Interval data types The Datetime data types are − DATE TIMESTAMP TIMESTAMP WITH TIME ZONE TIMESTAMP WITH LOCAL TIME ZONE The Interval data types are − INTERVAL YEAR TO MONTH INTERVAL DAY TO SECOND Field Values for Datetime and Interval Data Types Both datetime and interval data types consist of fields. The values of these fields determine the value of the data type. The following table lists the fields and their possible values for datetimes and intervals. Field Name Valid Datetime Values Valid Interval Values YEAR -4712 to 9999 (excluding year 0) Any nonzero integer MONTH 01 to 12 0 to 11 DAY 01 to 31 (limited by the values of MONTH and YEAR, according to the rules of the calendar for the locale) Any nonzero integer HOUR 00 to 23 0 to 23 MINUTE 00 to 59 0 to 59 SECOND 00 to 59.9(n), where 9(n) is the precision of time fractional seconds The 9(n) portion is not applicable for DATE. 0 to 59.9(n), where 9(n) is the precision of interval fractional seconds TIMEZONE_HOUR -12 to 14 (range accommodates daylight savings time changes) Not applicable for DATE or TIMESTAMP. Not applicable TIMEZONE_MINUTE 00 to 59 Not applicable for DATE or TIMESTAMP. Not applicable TIMEZONE_REGION Not applicable for DATE or TIMESTAMP. Not applicable TIMEZONE_ABBR Not applicable for DATE or TIMESTAMP. Not applicable The Datetime Data Types and Functions Following are the Datetime data types − DATE It stores date and time information in both character and number datatypes. It is made of information on century, year, month, date, hour, minute, and second. It is specified as − TIMESTAMP It is an extension of the DATE data type. It stores the year, month, and day of the DATE datatype, along with hour, minute, and second values. It is useful for storing precise time values. TIMESTAMP WITH TIME ZONE It is a variant of TIMESTAMP that includes a time zone region name or a time zone offset in its value. The time zone offset is the difference (in hours and minutes) between local time and UTC. This data type is useful for collecting and evaluating date information across geographic regions. TIMESTAMP WITH LOCAL TIME ZONE It is another variant of TIMESTAMP that includes a time zone offset in its value. Following table provides the Datetime functions (where, x has the datetime value) − S.No Function Name & Description 1 ADD_MONTHS(x, y); Adds y months to x. 2 LAST_DAY(x); Returns the last day of the month. 3 MONTHS_BETWEEN(x, y); Returns the number of months between x and y. 4 NEXT_DAY(x, day); Returns the datetime of the next day after x. 5 NEW_TIME; Returns the time/day value from a time zone specified by the user. 6 ROUND(x [, unit]); Rounds x. 7 SYSDATE(); Returns the current datetime. 8 TRUNC(x [, unit]); Truncates x. Timestamp functions (where, x has a timestamp value) − S.No Function Name & Description 1 CURRENT_TIMESTAMP(); Returns a TIMESTAMP WITH TIME ZONE containing the current session time along with the session time zone. 2 EXTRACT({ YEAR | MONTH | DAY | HOUR | MINUTE | SECOND } | { TIMEZONE_HOUR | TIMEZONE_MINUTE } | { TIMEZONE_REGION | } TIMEZONE_ABBR ) FROM x) Extracts and returns a year, month, day, hour, minute, second, or time zone from x. 3 FROM_TZ(x, time_zone); Converts the TIMESTAMP x and the time zone specified by time_zone to a TIMESTAMP WITH TIMEZONE. 4 LOCALTIMESTAMP(); Returns a TIMESTAMP containing the local time in the session time zone. 5 SYSTIMESTAMP(); Returns a TIMESTAMP WITH TIME ZONE containing the current database time along with the database time zone. 6 SYS_EXTRACT_UTC(x); Converts the TIMESTAMP WITH TIMEZONE x to a TIMESTAMP containing the date and time in UTC. 7 TO_TIMESTAMP(x, [format]); Converts the string x to a TIMESTAMP. 8 TO_TIMESTAMP_TZ(x, [format]); Converts the string x to a TIMESTAMP WITH TIMEZONE. Examples The following code snippets illustrate the use of the above functions − Example 1 SELECT SYSDATE FROM DUAL; Output − 08/31/2012 5:25:34 PM Example 2 SELECT TO_CHAR(CURRENT_DATE, ”DD-MM-YYYY HH:MI:SS”) FROM DUAL; Output − 31-08-2012 05:26:14 Example 3 SELECT ADD_MONTHS(SYSDATE, 5) FROM DUAL; Output − 01/31/2013 5:26:31 PM Example 4 SELECT LOCALTIMESTAMP FROM DUAL; Output − 8/31/2012 5:26:55.347000 PM The Interval Data Types and Functions Following are the Interval data types − IINTERVAL YEAR TO MONTH − It stores a period of time using the YEAR and MONTH datetime fields. INTERVAL DAY TO SECOND − It stores a period of time in terms of days, hours, minutes, and seconds. Interval Functions S.No Function Name & Description 1 NUMTODSINTERVAL(x, interval_unit); Converts the number x to an INTERVAL DAY TO SECOND. 2 NUMTOYMINTERVAL(x, interval_unit); Converts the number x to an INTERVAL YEAR TO MONTH. 3 TO_DSINTERVAL(x); Converts the string x to an INTERVAL DAY TO SECOND. 4 TO_YMINTERVAL(x); Converts the string x to an INTERVAL YEAR TO MONTH. Print Page Previous Next Advertisements ”;

PL/SQL – Object Oriented

PL/SQL – Object Oriented ”; Previous Next In this chapter, we will discuss Object-Oriented PL/SQL. PL/SQL allows defining an object type, which helps in designing object-oriented database in Oracle. An object type allows you to create composite types. Using objects allow you to implement real world objects with specific structure of data and methods for operating it. Objects have attributes and methods. Attributes are properties of an object and are used for storing an object”s state; and methods are used for modeling its behavior. Objects are created using the CREATE [OR REPLACE] TYPE statement. Following is an example to create a simple address object consisting of few attributes − CREATE OR REPLACE TYPE address AS OBJECT (house_no varchar2(10), street varchar2(30), city varchar2(20), state varchar2(10), pincode varchar2(10) ); / When the above code is executed at the SQL prompt, it produces the following result − Type created. Let”s create one more object customer where we will wrap attributes and methods together to have object-oriented feeling − CREATE OR REPLACE TYPE customer AS OBJECT (code number(5), name varchar2(30), contact_no varchar2(12), addr address, member procedure display ); / When the above code is executed at the SQL prompt, it produces the following result − Type created. Instantiating an Object Defining an object type provides a blueprint for the object. To use this object, you need to create instances of this object. You can access the attributes and methods of the object using the instance name and the access operator (.) as follows − DECLARE residence address; BEGIN residence := address(”103A”, ”M.G.Road”, ”Jaipur”, ”Rajasthan”,”201301”); dbms_output.put_line(”House No: ”|| residence.house_no); dbms_output.put_line(”Street: ”|| residence.street); dbms_output.put_line(”City: ”|| residence.city); dbms_output.put_line(”State: ”|| residence.state); dbms_output.put_line(”Pincode: ”|| residence.pincode); END; / When the above code is executed at the SQL prompt, it produces the following result − House No: 103A Street: M.G.Road City: Jaipur State: Rajasthan Pincode: 201301 PL/SQL procedure successfully completed. Member Methods Member methods are used for manipulating the attributes of the object. You provide the declaration of a member method while declaring the object type. The object body defines the code for the member methods. The object body is created using the CREATE TYPE BODY statement. Constructors are functions that return a new object as its value. Every object has a system defined constructor method. The name of the constructor is same as the object type. For example − residence := address(”103A”, ”M.G.Road”, ”Jaipur”, ”Rajasthan”,”201301”); The comparison methods are used for comparing objects. There are two ways to compare objects − Map method The Map method is a function implemented in such a way that its value depends upon the value of the attributes. For example, for a customer object, if the customer code is same for two customers, both customers could be the same. So the relationship between these two objects would depend upon the value of code. Order method The Order method implements some internal logic for comparing two objects. For example, for a rectangle object, a rectangle is bigger than another rectangle if both its sides are bigger. Using Map method Let us try to understand the above concepts using the following rectangle object − CREATE OR REPLACE TYPE rectangle AS OBJECT (length number, width number, member function enlarge( inc number) return rectangle, member procedure display, map member function measure return number ); / When the above code is executed at the SQL prompt, it produces the following result − Type created. Creating the type body − CREATE OR REPLACE TYPE BODY rectangle AS MEMBER FUNCTION enlarge(inc number) return rectangle IS BEGIN return rectangle(self.length + inc, self.width + inc); END enlarge; MEMBER PROCEDURE display IS BEGIN dbms_output.put_line(”Length: ”|| length); dbms_output.put_line(”Width: ”|| width); END display; MAP MEMBER FUNCTION measure return number IS BEGIN return (sqrt(length*length + width*width)); END measure; END; / When the above code is executed at the SQL prompt, it produces the following result − Type body created. Now using the rectangle object and its member functions − DECLARE r1 rectangle; r2 rectangle; r3 rectangle; inc_factor number := 5; BEGIN r1 := rectangle(3, 4); r2 := rectangle(5, 7); r3 := r1.enlarge(inc_factor); r3.display; IF (r1 > r2) THEN — calling measure function r1.display; ELSE r2.display; END IF; END; / When the above code is executed at the SQL prompt, it produces the following result − Length: 8 Width: 9 Length: 5 Width: 7 PL/SQL procedure successfully completed. Using Order method Now, the same effect could be achieved using an order method. Let us recreate the rectangle object using an order method − CREATE OR REPLACE TYPE rectangle AS OBJECT (length number, width number, member procedure display, order member function measure(r rectangle) return number ); / When the above code is executed at the SQL prompt, it produces the following result − Type created. Creating the type body − CREATE OR REPLACE TYPE BODY rectangle AS MEMBER PROCEDURE display IS BEGIN dbms_output.put_line(”Length: ”|| length); dbms_output.put_line(”Width: ”|| width); END display; ORDER MEMBER FUNCTION measure(r rectangle) return number IS BEGIN IF(sqrt(self.length*self.length + self.width*self.width)> sqrt(r.length*r.length + r.width*r.width)) then return(1); ELSE return(-1); END IF; END measure; END; / When the above code is executed at the SQL prompt, it produces the following result − Type body created. Using the rectangle object and its member functions − DECLARE r1 rectangle; r2 rectangle; BEGIN r1 := rectangle(23, 44); r2 := rectangle(15, 17); r1.display; r2.display; IF (r1 > r2) THEN — calling measure function r1.display; ELSE r2.display; END IF; END; / When the above code is executed at the SQL prompt, it produces the following result − Length: 23 Width: 44 Length: 15 Width: 17 Length: 23 Width: 44 PL/SQL procedure successfully completed. Inheritance for PL/SQL Objects PL/SQL allows creating object from the existing base objects. To implement inheritance, the base objects should be declared as NOT FINAL. The default is FINAL. The following programs illustrate the inheritance in PL/SQL Objects. Let us create another object named TableTop, this is inherited from the Rectangle object. For this, we need to create the base rectangle object − CREATE OR REPLACE TYPE rectangle

PL/SQL – Records

PL/SQL – Records ”; Previous Next In this chapter, we will discuss Records in PL/SQL. A record is a data structure that can hold data items of different kinds. Records consist of different fields, similar to a row of a database table. For example, you want to keep track of your books in a library. You might want to track the following attributes about each book, such as Title, Author, Subject, Book ID. A record containing a field for each of these items allows treating a BOOK as a logical unit and allows you to organize and represent its information in a better way. PL/SQL can handle the following types of records − Table-based Cursor-based records User-defined records Table-Based Records The %ROWTYPE attribute enables a programmer to create table-based and cursorbased records. The following example illustrates the concept of table-based records. We will be using the CUSTOMERS table we had created and used in the previous chapters − DECLARE customer_rec customers%rowtype; BEGIN SELECT * into customer_rec FROM customers WHERE id = 5; dbms_output.put_line(”Customer ID: ” || customer_rec.id); dbms_output.put_line(”Customer Name: ” || customer_rec.name); dbms_output.put_line(”Customer Address: ” || customer_rec.address); dbms_output.put_line(”Customer Salary: ” || customer_rec.salary); END; / When the above code is executed at the SQL prompt, it produces the following result − Customer ID: 5 Customer Name: Hardik Customer Address: Bhopal Customer Salary: 9000 PL/SQL procedure successfully completed. Cursor-Based Records The following example illustrates the concept of cursor-based records. We will be using the CUSTOMERS table we had created and used in the previous chapters − DECLARE CURSOR customer_cur is SELECT id, name, address FROM customers; customer_rec customer_cur%rowtype; BEGIN OPEN customer_cur; LOOP FETCH customer_cur into customer_rec; EXIT WHEN customer_cur%notfound; DBMS_OUTPUT.put_line(customer_rec.id || ” ” || customer_rec.name); END LOOP; END; / When the above code is executed at the SQL prompt, it produces the following result − 1 Ramesh 2 Khilan 3 kaushik 4 Chaitali 5 Hardik 6 Komal PL/SQL procedure successfully completed. User-Defined Records PL/SQL provides a user-defined record type that allows you to define the different record structures. These records consist of different fields. Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book − Title Author Subject Book ID Defining a Record The record type is defined as − TYPE type_name IS RECORD ( field_name1 datatype1 [NOT NULL] [:= DEFAULT EXPRESSION], field_name2 datatype2 [NOT NULL] [:= DEFAULT EXPRESSION], … field_nameN datatypeN [NOT NULL] [:= DEFAULT EXPRESSION); record-name type_name; The Book record is declared in the following way − DECLARE TYPE books IS RECORD (title varchar(50), author varchar(50), subject varchar(100), book_id number); book1 books; book2 books; Accessing Fields To access any field of a record, we use the dot (.) operator. The member access operator is coded as a period between the record variable name and the field that we wish to access. Following is an example to explain the usage of record − DECLARE type books is record (title varchar(50), author varchar(50), subject varchar(100), book_id number); book1 books; book2 books; BEGIN — Book 1 specification book1.title := ”C Programming”; book1.author := ”Nuha Ali ”; book1.subject := ”C Programming Tutorial”; book1.book_id := 6495407; — Book 2 specification book2.title := ”Telecom Billing”; book2.author := ”Zara Ali”; book2.subject := ”Telecom Billing Tutorial”; book2.book_id := 6495700; — Print book 1 record dbms_output.put_line(”Book 1 title : ”|| book1.title); dbms_output.put_line(”Book 1 author : ”|| book1.author); dbms_output.put_line(”Book 1 subject : ”|| book1.subject); dbms_output.put_line(”Book 1 book_id : ” || book1.book_id); — Print book 2 record dbms_output.put_line(”Book 2 title : ”|| book2.title); dbms_output.put_line(”Book 2 author : ”|| book2.author); dbms_output.put_line(”Book 2 subject : ”|| book2.subject); dbms_output.put_line(”Book 2 book_id : ”|| book2.book_id); END; / When the above code is executed at the SQL prompt, it produces the following result − Book 1 title : C Programming Book 1 author : Nuha Ali Book 1 subject : C Programming Tutorial Book 1 book_id : 6495407 Book 2 title : Telecom Billing Book 2 author : Zara Ali Book 2 subject : Telecom Billing Tutorial Book 2 book_id : 6495700 PL/SQL procedure successfully completed. Records as Subprogram Parameters You can pass a record as a subprogram parameter just as you pass any other variable. You can also access the record fields in the same way as you accessed in the above example − DECLARE type books is record (title varchar(50), author varchar(50), subject varchar(100), book_id number); book1 books; book2 books; PROCEDURE printbook (book books) IS BEGIN dbms_output.put_line (”Book title : ” || book.title); dbms_output.put_line(”Book author : ” || book.author); dbms_output.put_line( ”Book subject : ” || book.subject); dbms_output.put_line( ”Book book_id : ” || book.book_id); END; BEGIN — Book 1 specification book1.title := ”C Programming”; book1.author := ”Nuha Ali ”; book1.subject := ”C Programming Tutorial”; book1.book_id := 6495407; — Book 2 specification book2.title := ”Telecom Billing”; book2.author := ”Zara Ali”; book2.subject := ”Telecom Billing Tutorial”; book2.book_id := 6495700; — Use procedure to print book info printbook(book1); printbook(book2); END; / When the above code is executed at the SQL prompt, it produces the following result − Book title : C Programming Book author : Nuha Ali Book subject : C Programming Tutorial Book book_id : 6495407 Book title : Telecom Billing Book author : Zara Ali Book subject : Telecom Billing Tutorial Book book_id : 6495700 PL/SQL procedure successfully completed. Print Page Previous Next Advertisements ”;

PL/SQL – Packages

PL/SQL – Packages ”; Previous Next In this chapter, we will discuss the Packages in PL/SQL. Packages are schema objects that groups logically related PL/SQL types, variables, and subprograms. A package will have two mandatory parts − Package specification Package body or definition Package Specification The specification is the interface to the package. It just DECLARES the types, variables, constants, exceptions, cursors, and subprograms that can be referenced from outside the package. In other words, it contains all information about the content of the package, but excludes the code for the subprograms. All objects placed in the specification are called public objects. Any subprogram not in the package specification but coded in the package body is called a private object. The following code snippet shows a package specification having a single procedure. You can have many global variables defined and multiple procedures or functions inside a package. CREATE PACKAGE cust_sal AS PROCEDURE find_sal(c_id customers.id%type); END cust_sal; / When the above code is executed at the SQL prompt, it produces the following result − Package created. Package Body The package body has the codes for various methods declared in the package specification and other private declarations, which are hidden from the code outside the package. The CREATE PACKAGE BODY Statement is used for creating the package body. The following code snippet shows the package body declaration for the cust_sal package created above. I assumed that we already have CUSTOMERS table created in our database as mentioned in the PL/SQL – Variables chapter. CREATE OR REPLACE PACKAGE BODY cust_sal AS PROCEDURE find_sal(c_id customers.id%TYPE) IS c_sal customers.salary%TYPE; BEGIN SELECT salary INTO c_sal FROM customers WHERE id = c_id; dbms_output.put_line(”Salary: ”|| c_sal); END find_sal; END cust_sal; / When the above code is executed at the SQL prompt, it produces the following result − Package body created. Using the Package Elements The package elements (variables, procedures or functions) are accessed with the following syntax − package_name.element_name; Consider, we already have created the above package in our database schema, the following program uses the find_sal method of the cust_sal package − DECLARE code customers.id%type := &cc_id; BEGIN cust_sal.find_sal(code); END; / When the above code is executed at the SQL prompt, it prompts to enter the customer ID and when you enter an ID, it displays the corresponding salary as follows − Enter value for cc_id: 1 Salary: 3000 PL/SQL procedure successfully completed. Example The following program provides a more complete package. We will use the CUSTOMERS table stored in our database with the following records − Select * from customers; +—-+———-+—–+———–+———-+ | ID | NAME | AGE | ADDRESS | SALARY | +—-+———-+—–+———–+———-+ | 1 | Ramesh | 32 | Ahmedabad | 3000.00 | | 2 | Khilan | 25 | Delhi | 3000.00 | | 3 | kaushik | 23 | Kota | 3000.00 | | 4 | Chaitali | 25 | Mumbai | 7500.00 | | 5 | Hardik | 27 | Bhopal | 9500.00 | | 6 | Komal | 22 | MP | 5500.00 | +—-+———-+—–+———–+———-+ The Package Specification CREATE OR REPLACE PACKAGE c_package AS — Adds a customer PROCEDURE addCustomer(c_id customers.id%type, c_name customers.Name%type, c_age customers.age%type, c_addr customers.address%type, c_sal customers.salary%type); — Removes a customer PROCEDURE delCustomer(c_id customers.id%TYPE); –Lists all customers PROCEDURE listCustomer; END c_package; / When the above code is executed at the SQL prompt, it creates the above package and displays the following result − Package created. Creating the Package Body CREATE OR REPLACE PACKAGE BODY c_package AS PROCEDURE addCustomer(c_id customers.id%type, c_name customers.Name%type, c_age customers.age%type, c_addr customers.address%type, c_sal customers.salary%type) IS BEGIN INSERT INTO customers (id,name,age,address,salary) VALUES(c_id, c_name, c_age, c_addr, c_sal); END addCustomer; PROCEDURE delCustomer(c_id customers.id%type) IS BEGIN DELETE FROM customers WHERE id = c_id; END delCustomer; PROCEDURE listCustomer IS CURSOR c_customers is SELECT name FROM customers; TYPE c_list is TABLE OF customers.Name%type; name_list c_list := c_list(); counter integer :=0; BEGIN FOR n IN c_customers LOOP counter := counter +1; name_list.extend; name_list(counter) := n.name; dbms_output.put_line(”Customer(” ||counter|| ”)”||name_list(counter)); END LOOP; END listCustomer; END c_package; / The above example makes use of the nested table. We will discuss the concept of nested table in the next chapter. When the above code is executed at the SQL prompt, it produces the following result − Package body created. Using The Package The following program uses the methods declared and defined in the package c_package. DECLARE code customers.id%type:= 8; BEGIN c_package.addcustomer(7, ”Rajnish”, 25, ”Chennai”, 3500); c_package.addcustomer(8, ”Subham”, 32, ”Delhi”, 7500); c_package.listcustomer; c_package.delcustomer(code); c_package.listcustomer; END; / When the above code is executed at the SQL prompt, it produces the following result − Customer(1): Ramesh Customer(2): Khilan Customer(3): kaushik Customer(4): Chaitali Customer(5): Hardik Customer(6): Komal Customer(7): Rajnish Customer(8): Subham Customer(1): Ramesh Customer(2): Khilan Customer(3): kaushik Customer(4): Chaitali Customer(5): Hardik Customer(6): Komal Customer(7): Rajnish PL/SQL procedure successfully completed Print Page Previous Next Advertisements ”;

PL/SQL – DBMS Output

PL/SQL – DBMS Output ”; Previous Next In this chapter, we will discuss the DBMS Output in PL/SQL. The DBMS_OUTPUT is a built-in package that enables you to display output, debugging information, and send messages from PL/SQL blocks, subprograms, packages, and triggers. We have already used this package throughout our tutorial. Let us look at a small code snippet that will display all the user tables in the database. Try it in your database to list down all the table names − BEGIN dbms_output.put_line (user || ” Tables in the database:”); FOR t IN (SELECT table_name FROM user_tables) LOOP dbms_output.put_line(t.table_name); END LOOP; END; / DBMS_OUTPUT Subprograms The DBMS_OUTPUT package has the following subprograms − S.No Subprogram & Purpose 1 DBMS_OUTPUT.DISABLE; Disables message output. 2 DBMS_OUTPUT.ENABLE(buffer_size IN INTEGER DEFAULT 20000); Enables message output. A NULL value of buffer_size represents unlimited buffer size. 3 DBMS_OUTPUT.GET_LINE (line OUT VARCHAR2, status OUT INTEGER); Retrieves a single line of buffered information. 4 DBMS_OUTPUT.GET_LINES (lines OUT CHARARR, numlines IN OUT INTEGER); Retrieves an array of lines from the buffer. 5 DBMS_OUTPUT.NEW_LINE; Puts an end-of-line marker. 6 DBMS_OUTPUT.PUT(item IN VARCHAR2); Places a partial line in the buffer. 7 DBMS_OUTPUT.PUT_LINE(item IN VARCHAR2); Places a line in the buffer. Example DECLARE lines dbms_output.chararr; num_lines number; BEGIN — enable the buffer with default size 20000 dbms_output.enable; dbms_output.put_line(”Hello Reader!”); dbms_output.put_line(”Hope you have enjoyed the tutorials!”); dbms_output.put_line(”Have a great time exploring pl/sql!”); num_lines := 3; dbms_output.get_lines(lines, num_lines); FOR i IN 1..num_lines LOOP dbms_output.put_line(lines(i)); END LOOP; END; / When the above code is executed at the SQL prompt, it produces the following result − Hello Reader! Hope you have enjoyed the tutorials! Have a great time exploring pl/sql! PL/SQL procedure successfully completed. Print Page Previous Next Advertisements ”;

PL/SQL – Functions

PL/SQL – Functions ”; Previous Next In this chapter, we will discuss the functions in PL/SQL. A function is same as a procedure except that it returns a value. Therefore, all the discussions of the previous chapter are true for functions too. Creating a Function A standalone function is created using the CREATE FUNCTION statement. The simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as follows − CREATE [OR REPLACE] FUNCTION function_name [(parameter_name [IN | OUT | IN OUT] type [, …])] RETURN return_datatype {IS | AS} BEGIN < function_body > END [function_name]; Where, function-name specifies the name of the function. [OR REPLACE] option allows the modification of an existing function. The optional parameter list contains name, mode and types of the parameters. IN represents the value that will be passed from outside and OUT represents the parameter that will be used to return a value outside of the procedure. The function must contain a return statement. The RETURN clause specifies the data type you are going to return from the function. function-body contains the executable part. The AS keyword is used instead of the IS keyword for creating a standalone function. Example The following example illustrates how to create and call a standalone function. This function returns the total number of CUSTOMERS in the customers table. We will use the CUSTOMERS table, which we had created in the PL/SQL Variables chapter − Select * from customers; +—-+———-+—–+———–+———-+ | ID | NAME | AGE | ADDRESS | SALARY | +—-+———-+—–+———–+———-+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | +—-+———-+—–+———–+———-+ CREATE OR REPLACE FUNCTION totalCustomers RETURN number IS total number(2) := 0; BEGIN SELECT count(*) into total FROM customers; RETURN total; END; / When the above code is executed using the SQL prompt, it will produce the following result − Function created. Calling a Function While creating a function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task. When a program calls a function, the program control is transferred to the called function. A called function performs the defined task and when its return statement is executed or when the last end statement is reached, it returns the program control back to the main program. To call a function, you simply need to pass the required parameters along with the function name and if the function returns a value, then you can store the returned value. Following program calls the function totalCustomers from an anonymous block − DECLARE c number(2); BEGIN c := totalCustomers(); dbms_output.put_line(”Total no. of Customers: ” || c); END; / When the above code is executed at the SQL prompt, it produces the following result − Total no. of Customers: 6 PL/SQL procedure successfully completed. Example The following example demonstrates Declaring, Defining, and Invoking a Simple PL/SQL Function that computes and returns the maximum of two values. DECLARE a number; b number; c number; FUNCTION findMax(x IN number, y IN number) RETURN number IS z number; BEGIN IF x > y THEN z:= x; ELSE Z:= y; END IF; RETURN z; END; BEGIN a:= 23; b:= 45; c := findMax(a, b); dbms_output.put_line(” Maximum of (23,45): ” || c); END; / When the above code is executed at the SQL prompt, it produces the following result − Maximum of (23,45): 45 PL/SQL procedure successfully completed. PL/SQL Recursive Functions We have seen that a program or subprogram may call another subprogram. When a subprogram calls itself, it is referred to as a recursive call and the process is known as recursion. To illustrate the concept, let us calculate the factorial of a number. Factorial of a number n is defined as − n! = n*(n-1)! = n*(n-1)*(n-2)! … = n*(n-1)*(n-2)*(n-3)… 1 The following program calculates the factorial of a given number by calling itself recursively − DECLARE num number; factorial number; FUNCTION fact(x number) RETURN number IS f number; BEGIN IF x=0 THEN f := 1; ELSE f := x * fact(x-1); END IF; RETURN f; END; BEGIN num:= 6; factorial := fact(num); dbms_output.put_line(” Factorial ”|| num || ” is ” || factorial); END; / When the above code is executed at the SQL prompt, it produces the following result − Factorial 6 is 720 PL/SQL procedure successfully completed. Print Page Previous Next Advertisements ”;