Category: plsql

  • Khóa học miễn phí PL/SQL – Arrays nhận dự án làm có lương

    PL/SQL – Arrays



    In this chapter, we will discuss arrays in PL/SQL. The PL/SQL programming language provides a data structure called the VARRAY, which can store a fixed-size sequential collection of elements of the same type. A varray is used to store an ordered collection of data, however it is often better to think of an array as a collection of variables of the same type.

    All varrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

    Varrays in PL/SQL

    An array is a part of collection type data and it stands for variable-size arrays. We will study other collection types in a later chapter ”PL/SQL Collections”.

    Each element in a varray has an index associated with it. It also has a maximum size that can be changed dynamically.

    Creating a Varray Type

    A varray type is created with the CREATE TYPE statement. You must specify the maximum size and the type of elements stored in the varray.

    The basic syntax for creating a VARRAY type at the schema level is −

    CREATE OR REPLACE TYPE varray_type_name IS VARRAY(n) of <element_type>
    

    Where,

    • varray_type_name is a valid attribute name,
    • n is the number of elements (maximum) in the varray,
    • element_type is the data type of the elements of the array.

    Maximum size of a varray can be changed using the ALTER TYPE statement.

    For example,

    CREATE Or REPLACE TYPE namearray AS VARRAY(3) OF VARCHAR2(10);
    /
    
    Type created.
    

    The basic syntax for creating a VARRAY type within a PL/SQL block is −

    TYPE varray_type_name IS VARRAY(n) of <element_type>
    

    For example −

    TYPE namearray IS VARRAY(5) OF VARCHAR2(10);
    Type grades IS VARRAY(5) OF INTEGER;
    

    Let us now work out on a few examples to understand the concept −

    Example 1

    The following program illustrates the use of varrays −

    DECLARE
       type namesarray IS VARRAY(5) OF VARCHAR2(10);
       type grades IS VARRAY(5) OF INTEGER;
       names namesarray;
       marks grades;
       total integer;
    BEGIN
       names := namesarray(''Kavita'', ''Pritam'', ''Ayan'', ''Rishav'', ''Aziz'');
       marks:= grades(98, 97, 78, 87, 92);
       total := names.count;
       dbms_output.put_line(''Total ''|| total || '' Students'');
       FOR i in 1 .. total LOOP
          dbms_output.put_line(''Student: '' || names(i) || ''
          Marks: '' || marks(i));
       END LOOP;
    END;
    /
    

    When the above code is executed at the SQL prompt, it produces the following result −

    Total 5 Students
    Student: Kavita  Marks: 98
    Student: Pritam  Marks: 97
    Student: Ayan  Marks: 78
    Student: Rishav  Marks: 87
    Student: Aziz  Marks: 92
    
    PL/SQL procedure successfully completed.
    

    Please note

    • In Oracle environment, the starting index for varrays is always 1.

    • You can initialize the varray elements using the constructor method of the varray type, which has the same name as the varray.

    • Varrays are one-dimensional arrays.

    • A varray is automatically NULL when it is declared and must be initialized before its elements can be referenced.

    Example 2

    Elements of a varray could also be a %ROWTYPE of any database table or %TYPE of any database table field. The following example illustrates the concept.

    We will use the CUSTOMERS table stored in our database as −

    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 |
    +----+----------+-----+-----------+----------+
    

    Following example makes the use of cursor, which you will study in detail in a separate chapter.

    DECLARE
       CURSOR c_customers is
       SELECT  name FROM customers;
       type c_list is varray (6) 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;
    /
    

    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
    
    PL/SQL procedure successfully completed.
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí PL/SQL – Cursors nhận dự án làm có lương

    PL/SQL – Cursors



    In this chapter, we will discuss the cursors in PL/SQL. Oracle creates a memory area, known as the context area, for processing an SQL statement, which contains all the information needed for processing the statement; for example, the number of rows processed, etc.

    A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A cursor holds the rows (one or more) returned by a SQL statement. The set of rows the cursor holds is referred to as the active set.

    You can name a cursor so that it could be referred to in a program to fetch and process the rows returned by the SQL statement, one at a time. There are two types of cursors −

    • Implicit cursors
    • Explicit cursors

    Implicit Cursors

    Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when there is no explicit cursor for the statement. Programmers cannot control the implicit cursors and the information in it.

    Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is associated with this statement. For INSERT operations, the cursor holds the data that needs to be inserted. For UPDATE and DELETE operations, the cursor identifies the rows that would be affected.

    In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always has attributes such as %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT. The SQL cursor has additional attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS, designed for use with the FORALL statement. The following table provides the description of the most used attributes −

    S.No Attribute & Description
    1

    %FOUND

    Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows or a SELECT INTO statement returned one or more rows. Otherwise, it returns FALSE.

    2

    %NOTFOUND

    The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or DELETE statement affected no rows, or a SELECT INTO statement returned no rows. Otherwise, it returns FALSE.

    3

    %ISOPEN

    Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor automatically after executing its associated SQL statement.

    4

    %ROWCOUNT

    Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or returned by a SELECT INTO statement.

    Any SQL cursor attribute will be accessed as sql%attribute_name as shown below in the example.

    Example

    We will be using the CUSTOMERS table we had created and used in the previous chapters.

    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 |
    +----+----------+-----+-----------+----------+
    

    The following program will update the table and increase the salary of each customer by 500 and use the SQL%ROWCOUNT attribute to determine the number of rows affected −

    DECLARE
       total_rows number(2);
    BEGIN
       UPDATE customers
       SET salary = salary + 500;
       IF sql%notfound THEN
          dbms_output.put_line(''no customers selected'');
       ELSIF sql%found THEN
          total_rows := sql%rowcount;
          dbms_output.put_line( total_rows || '' customers selected '');
       END IF;
    END;
    /
    

    When the above code is executed at the SQL prompt, it produces the following result −

    6 customers selected
    
    PL/SQL procedure successfully completed.
    

    If you check the records in customers table, you will find that the rows have been updated −

    Select * from customers;
    
    +----+----------+-----+-----------+----------+
    | ID | NAME     | AGE | ADDRESS   | SALARY   |
    +----+----------+-----+-----------+----------+
    |  1 | Ramesh   |  32 | Ahmedabad |  2500.00 |
    |  2 | Khilan   |  25 | Delhi     |  2000.00 |
    |  3 | kaushik  |  23 | Kota      |  2500.00 |
    |  4 | Chaitali |  25 | Mumbai    |  7000.00 |
    |  5 | Hardik   |  27 | Bhopal    |  9000.00 |
    |  6 | Komal    |  22 | MP        |  5000.00 |
    +----+----------+-----+-----------+----------+
    

    Explicit Cursors

    Explicit cursors are programmer-defined cursors for gaining more control over the context area. An explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created on a SELECT Statement which returns more than one row.

    The syntax for creating an explicit cursor is −

    CURSOR cursor_name IS select_statement;
    

    Working with an explicit cursor includes the following steps −

    • Declaring the cursor for initializing the memory
    • Opening the cursor for allocating the memory
    • Fetching the cursor for retrieving the data
    • Closing the cursor to release the allocated memory

    Declaring the Cursor

    Declaring the cursor defines the cursor with a name and the associated SELECT statement. For example −

    CURSOR c_customers IS
       SELECT id, name, address FROM customers;
    

    Opening the Cursor

    Opening the cursor allocates the memory for the cursor and makes it ready for fetching the rows returned by the SQL statement into it. For example, we will open the above defined cursor as follows −

    OPEN c_customers;
    

    Fetching the Cursor

    Fetching the cursor involves accessing one row at a time. For example, we will fetch rows from the above-opened cursor as follows −

    FETCH c_customers INTO c_id, c_name, c_addr;
    

    Closing the Cursor

    Closing the cursor means releasing the allocated memory. For example, we will close the above-opened cursor as follows −

    CLOSE c_customers;
    

    Example

    Following is a complete example to illustrate the concepts of explicit cursors &minua;

    DECLARE
       c_id customers.id%type;
       c_name customers.name%type;
       c_addr customers.address%type;
       CURSOR c_customers is
          SELECT id, name, address FROM customers;
    BEGIN
       OPEN c_customers;
       LOOP
       FETCH c_customers into c_id, c_name, c_addr;
          EXIT WHEN c_customers%notfound;
          dbms_output.put_line(c_id || '' '' || c_name || '' '' || c_addr);
       END LOOP;
       CLOSE c_customers;
    END;
    /
    

    When the above code is executed at the SQL prompt, it produces the following result −

    1 Ramesh Ahmedabad
    2 Khilan Delhi
    3 kaushik Kota
    4 Chaitali Mumbai
    5 Hardik Bhopal
    6 Komal MP
    
    PL/SQL procedure successfully completed.
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí PL/SQL – Exceptions nhận dự án làm có lương

    PL/SQL – Exceptions



    In this chapter, we will discuss Exceptions in PL/SQL. An exception is an error condition during a program execution. PL/SQL supports programmers to catch such conditions using EXCEPTION block in the program and an appropriate action is taken against the error condition. There are two types of exceptions −

    • System-defined exceptions
    • User-defined exceptions

    Syntax for Exception Handling

    The general syntax for exception handling is as follows. Here you can list down as many exceptions as you can handle. The default exception will be handled using WHEN others THEN

    DECLARE
       <declarations section>
    BEGIN
       <executable command(s)>
    EXCEPTION
       <exception handling goes here >
       WHEN exception1 THEN
          exception1-handling-statements
       WHEN exception2  THEN
          exception2-handling-statements
       WHEN exception3 THEN
          exception3-handling-statements
       ........
       WHEN others THEN
          exception3-handling-statements
    END;
    

    Example

    Let us write a code to illustrate the concept. We will be using the CUSTOMERS table we had created and used in the previous chapters −

    DECLARE
       c_id customers.id%type := 8;
       c_name customerS.Name%type;
       c_addr customers.address%type;
    BEGIN
       SELECT  name, address INTO  c_name, c_addr
       FROM customers
       WHERE id = c_id;
       DBMS_OUTPUT.PUT_LINE (''Name: ''||  c_name);
       DBMS_OUTPUT.PUT_LINE (''Address: '' || c_addr);
    
    EXCEPTION
       WHEN no_data_found THEN
          dbms_output.put_line(''No such customer!'');
       WHEN others THEN
          dbms_output.put_line(''Error!'');
    END;
    /
    

    When the above code is executed at the SQL prompt, it produces the following result −

    No such customer!
    
    PL/SQL procedure successfully completed.
    

    The above program displays the name and address of a customer whose ID is given. Since there is no customer with ID value 8 in our database, the program raises the run-time exception NO_DATA_FOUND, which is captured in the EXCEPTION block.

    Raising Exceptions

    Exceptions are raised by the database server automatically whenever there is any internal database error, but exceptions can be raised explicitly by the programmer by using the command RAISE. Following is the simple syntax for raising an exception −

    DECLARE
       exception_name EXCEPTION;
    BEGIN
       IF condition THEN
          RAISE exception_name;
       END IF;
    EXCEPTION
       WHEN exception_name THEN
       statement;
    END;
    

    You can use the above syntax in raising the Oracle standard exception or any user-defined exception. In the next section, we will give you an example on raising a user-defined exception. You can raise the Oracle standard exceptions in a similar way.

    User-defined Exceptions

    PL/SQL allows you to define your own exceptions according to the need of your program. A user-defined exception must be declared and then raised explicitly, using either a RAISE statement or the procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.

    The syntax for declaring an exception is −

    DECLARE
       my-exception EXCEPTION;
    

    Example

    The following example illustrates the concept. This program asks for a customer ID, when the user enters an invalid ID, the exception invalid_id is raised.

    DECLARE
       c_id customers.id%type := &cc_id;
       c_name customerS.Name%type;
       c_addr customers.address%type;
       -- user defined exception
       ex_invalid_id  EXCEPTION;
    BEGIN
       IF c_id <= 0 THEN
          RAISE ex_invalid_id;
       ELSE
          SELECT  name, address INTO  c_name, c_addr
          FROM customers
          WHERE id = c_id;
          DBMS_OUTPUT.PUT_LINE (''Name: ''||  c_name);
          DBMS_OUTPUT.PUT_LINE (''Address: '' || c_addr);
       END IF;
    
    EXCEPTION
       WHEN ex_invalid_id THEN
          dbms_output.put_line(''ID must be greater than zero!'');
       WHEN no_data_found THEN
          dbms_output.put_line(''No such customer!'');
       WHEN others THEN
          dbms_output.put_line(''Error!'');
    END;
    /
    

    When the above code is executed at the SQL prompt, it produces the following result −

    Enter value for cc_id: -6 (let''s enter a value -6)
    old  2: c_id customers.id%type := &cc_id;
    new  2: c_id customers.id%type := -6;
    ID must be greater than zero!
    
    PL/SQL procedure successfully completed.
    

    Pre-defined Exceptions

    PL/SQL provides many pre-defined exceptions, which are executed when any database rule is violated by a program. For example, the predefined exception NO_DATA_FOUND is raised when a SELECT INTO statement returns no rows. The following table lists few of the important pre-defined exceptions −

    Exception Oracle Error SQLCODE Description
    ACCESS_INTO_NULL 06530 -6530 It is raised when a null object is automatically assigned a value.
    CASE_NOT_FOUND 06592 -6592 It is raised when none of the choices in the WHEN clause of a CASE statement is selected, and there is no ELSE clause.
    COLLECTION_IS_NULL 06531 -6531 It is raised when a program attempts to apply collection methods other than EXISTS to an uninitialized nested table or varray, or the program attempts to assign values to the elements of an uninitialized nested table or varray.
    DUP_VAL_ON_INDEX 00001 -1 It is raised when duplicate values are attempted to be stored in a column with unique index.
    INVALID_CURSOR 01001 -1001 It is raised when attempts are made to make a cursor operation that is not allowed, such as closing an unopened cursor.
    INVALID_NUMBER 01722 -1722 It is raised when the conversion of a character string into a number fails because the string does not represent a valid number.
    LOGIN_DENIED 01017 -1017 It is raised when a program attempts to log on to the database with an invalid username or password.
    NO_DATA_FOUND 01403 +100 It is raised when a SELECT INTO statement returns no rows.
    NOT_LOGGED_ON 01012 -1012 It is raised when a database call is issued without being connected to the database.
    PROGRAM_ERROR 06501 -6501 It is raised when PL/SQL has an internal problem.
    ROWTYPE_MISMATCH 06504 -6504 It is raised when a cursor fetches value in a variable having incompatible data type.
    SELF_IS_NULL 30625 -30625 It is raised when a member method is invoked, but the instance of the object type was not initialized.
    STORAGE_ERROR 06500 -6500 It is raised when PL/SQL ran out of memory or memory was corrupted.
    TOO_MANY_ROWS 01422 -1422 It is raised when a SELECT INTO statement returns more than one row.
    VALUE_ERROR 06502 -6502 It is raised when an arithmetic, conversion, truncation, or sizeconstraint error occurs.
    ZERO_DIVIDE 01476 1476 It is raised when an attempt is made to divide a number by zero.

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí PL/SQL – Triggers nhận dự án làm có lương

    PL/SQL – Triggers



    In this chapter, we will discuss Triggers in PL/SQL. Triggers are stored programs, which are automatically executed or fired when some events occur. Triggers are, in fact, written to be executed in response to any of the following events −

    • A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)

    • A database definition (DDL) statement (CREATE, ALTER, or DROP).

    • A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).

    Triggers can be defined on the table, view, schema, or database with which the event is associated.

    Benefits of Triggers

    Triggers can be written for the following purposes −

    • Generating some derived column values automatically
    • Enforcing referential integrity
    • Event logging and storing information on table access
    • Auditing
    • Synchronous replication of tables
    • Imposing security authorizations
    • Preventing invalid transactions

    Creating Triggers

    The syntax for creating a trigger is −

    CREATE [OR REPLACE ] TRIGGER trigger_name
    {BEFORE | AFTER | INSTEAD OF }
    {INSERT [OR] | UPDATE [OR] | DELETE}
    [OF col_name]
    ON table_name
    [REFERENCING OLD AS o NEW AS n]
    [FOR EACH ROW]
    WHEN (condition)
    DECLARE
       Declaration-statements
    BEGIN
       Executable-statements
    EXCEPTION
       Exception-handling-statements
    END;
    

    Where,

    • CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing trigger with the trigger_name.

    • {BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be executed. The INSTEAD OF clause is used for creating trigger on a view.

    • {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.

    • [OF col_name] − This specifies the column name that will be updated.

    • [ON table_name] − This specifies the name of the table associated with the trigger.

    • [REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old values for various DML statements, such as INSERT, UPDATE, and DELETE.

    • [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be executed for each row being affected. Otherwise the trigger will execute just once when the SQL statement is executed, which is called a table level trigger.

    • WHEN (condition) − This provides a condition for rows for which the trigger would fire. This clause is valid only for row-level triggers.

    Example

    To start with, we will be using the CUSTOMERS table we had created and used in the previous chapters −

    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 |
    +----+----------+-----+-----------+----------+
    

    The following program creates a row-level trigger for the customers table that would fire for INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This trigger will display the salary difference between the old values and new values −

    CREATE OR REPLACE TRIGGER display_salary_changes
    BEFORE DELETE OR INSERT OR UPDATE ON customers
    FOR EACH ROW
    WHEN (NEW.ID > 0)
    DECLARE
       sal_diff number;
    BEGIN
       sal_diff := :NEW.salary  - :OLD.salary;
       dbms_output.put_line(''Old salary: '' || :OLD.salary);
       dbms_output.put_line(''New salary: '' || :NEW.salary);
       dbms_output.put_line(''Salary difference: '' || sal_diff);
    END;
    /
    

    When the above code is executed at the SQL prompt, it produces the following result −

    Trigger created.
    

    The following points need to be considered here −

    • OLD and NEW references are not available for table-level triggers, rather you can use them for record-level triggers.

    • If you want to query the table in the same trigger, then you should use the AFTER keyword, because triggers can query the table or change it again only after the initial changes are applied and the table is back in a consistent state.

    • The above trigger has been written in such a way that it will fire before any DELETE or INSERT or UPDATE operation on the table, but you can write your trigger on a single or multiple operations, for example BEFORE DELETE, which will fire whenever a record will be deleted using the DELETE operation on the table.

    Triggering a Trigger

    Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT statement, which will create a new record in the table −

    INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
    VALUES (7, ''Kriti'', 22, ''HP'', 7500.00 );
    

    When a record is created in the CUSTOMERS table, the above create trigger, display_salary_changes will be fired and it will display the following result −

    Old salary:
    New salary: 7500
    Salary difference:
    

    Because this is a new record, old salary is not available and the above result comes as null. Let us now perform one more DML operation on the CUSTOMERS table. The UPDATE statement will update an existing record in the table −

    UPDATE customers
    SET salary = salary + 500
    WHERE id = 2;
    

    When a record is updated in the CUSTOMERS table, the above create trigger, display_salary_changes will be fired and it will display the following result −

    Old salary: 1500
    New salary: 2000
    Salary difference: 500
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí PL/SQL – Records nhận dự án làm có lương

    PL/SQL – Records



    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.
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí PL/SQL – Packages nhận dự án làm có lương

    PL/SQL – Packages



    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 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
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí PL/SQL – Collections nhận dự án làm có lương

    PL/SQL – Collections



    In this chapter, we will discuss the Collections in PL/SQL. A collection is an ordered group of elements having the same data type. Each element is identified by a unique subscript that represents its position in the collection.

    PL/SQL provides three collection types −

    • Index-by tables or Associative array
    • Nested table
    • Variable-size array or Varray

    Oracle documentation provides the following characteristics for each type of collections −

    Collection Type Number of Elements Subscript Type Dense or Sparse Where Created Can Be Object Type Attribute
    Associative array (or index-by table) Unbounded String or integer Either Only in PL/SQL block No
    Nested table Unbounded Integer Starts dense, can become sparse Either in PL/SQL block or at schema level Yes
    Variablesize array (Varray) Bounded Integer Always dense Either in PL/SQL block or at schema level Yes

    We have already discussed varray in the chapter ”PL/SQL arrays”. In this chapter, we will discuss the PL/SQL tables.

    Both types of PL/SQL tables, i.e., the index-by tables and the nested tables have the same structure and their rows are accessed using the subscript notation. However, these two types of tables differ in one aspect; the nested tables can be stored in a database column and the index-by tables cannot.

    Index-By Table

    An index-by table (also called an associative array) is a set of key-value pairs. Each key is unique and is used to locate the corresponding value. The key can be either an integer or a string.

    An index-by table is created using the following syntax. Here, we are creating an index-by table named table_name, the keys of which will be of the subscript_type and associated values will be of the element_type

    TYPE type_name IS TABLE OF element_type [NOT NULL] INDEX BY subscript_type;
    
    table_name type_name;
    

    Example

    Following example shows how to create a table to store integer values along with names and later it prints the same list of names.

    DECLARE
       TYPE salary IS TABLE OF NUMBER INDEX BY VARCHAR2(20);
       salary_list salary;
       name   VARCHAR2(20);
    BEGIN
       -- adding elements to the table
       salary_list(''Rajnish'') := 62000;
       salary_list(''Minakshi'') := 75000;
       salary_list(''Martin'') := 100000;
       salary_list(''James'') := 78000;
    
       -- printing the table
       name := salary_list.FIRST;
       WHILE name IS NOT null LOOP
          dbms_output.put_line
          (''Salary of '' || name || '' is '' || TO_CHAR(salary_list(name)));
          name := salary_list.NEXT(name);
       END LOOP;
    END;
    /
    

    When the above code is executed at the SQL prompt, it produces the following result −

    Salary of James is 78000
    Salary of Martin is 100000
    Salary of Minakshi is 75000
    Salary of Rajnish is 62000
    
    PL/SQL procedure successfully completed.
    

    Example

    Elements of an index-by table could also be a %ROWTYPE of any database table or %TYPE of any database table field. The following example illustrates the concept. We will use the CUSTOMERS table stored in our database as −

    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 |
    +----+----------+-----+-----------+----------+
    

    DECLARE
       CURSOR c_customers is
          select name from customers;
    
       TYPE c_list IS TABLE of customers.Name%type INDEX BY binary_integer;
       name_list c_list;
       counter integer :=0;
    BEGIN
       FOR n IN c_customers LOOP
          counter := counter +1;
          name_list(counter) := n.name;
          dbms_output.put_line(''Customer(''||counter||''):''||name_lis t(counter));
       END LOOP;
    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
    
    PL/SQL procedure successfully completed
    

    Nested Tables

    A nested table is like a one-dimensional array with an arbitrary number of elements. However, a nested table differs from an array in the following aspects −

    • An array has a declared number of elements, but a nested table does not. The size of a nested table can increase dynamically.

    • An array is always dense, i.e., it always has consecutive subscripts. A nested array is dense initially, but it can become sparse when elements are deleted from it.

    A nested table is created using the following syntax −

    TYPE type_name IS TABLE OF element_type [NOT NULL];
    
    table_name type_name;
    

    This declaration is similar to the declaration of an index-by table, but there is no INDEX BY clause.

    A nested table can be stored in a database column. It can further be used for simplifying SQL operations where you join a single-column table with a larger table. An associative array cannot be stored in the database.

    Example

    The following examples illustrate the use of nested table −

    DECLARE
       TYPE names_table IS TABLE OF VARCHAR2(10);
       TYPE grades IS TABLE OF INTEGER;
       names names_table;
       marks grades;
       total integer;
    BEGIN
       names := names_table(''Kavita'', ''Pritam'', ''Ayan'', ''Rishav'', ''Aziz'');
       marks:= grades(98, 97, 78, 87, 92);
       total := names.count;
       dbms_output.put_line(''Total ''|| total || '' Students'');
       FOR i IN 1 .. total LOOP
          dbms_output.put_line(''Student:''||names(i)||'', Marks:'' || marks(i));
       end loop;
    END;
    /
    

    When the above code is executed at the SQL prompt, it produces the following result −

    Total 5 Students
    Student:Kavita, Marks:98
    Student:Pritam, Marks:97
    Student:Ayan, Marks:78
    Student:Rishav, Marks:87
    Student:Aziz, Marks:92
    
    PL/SQL procedure successfully completed.
    

    Example

    Elements of a nested table can also be a %ROWTYPE of any database table or %TYPE of any database table field. The following example illustrates the concept. We will use the CUSTOMERS table stored in our database as −

    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 |
    +----+----------+-----+-----------+----------+
    

    DECLARE
       CURSOR c_customers is
          SELECT  name FROM customers;
       TYPE c_list IS TABLE of customerS.No.ame%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;
    /
    

    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
    
    PL/SQL procedure successfully completed.
    

    Collection Methods

    PL/SQL provides the built-in collection methods that make collections easier to use. The following table lists the methods and their purpose −

    S.No Method Name & Purpose
    1

    EXISTS(n)

    Returns TRUE if the nth element in a collection exists; otherwise returns FALSE.

    2

    COUNT

    Returns the number of elements that a collection currently contains.

    3

    LIMIT

    Checks the maximum size of a collection.

    4

    FIRST

    Returns the first (smallest) index numbers in a collection that uses the integer subscripts.

    5

    LAST

    Returns the last (largest) index numbers in a collection that uses the integer subscripts.

    6

    PRIOR(n)

    Returns the index number that precedes index n in a collection.

    7

    NEXT(n)

    Returns the index number that succeeds index n.

    8

    EXTEND

    Appends one null element to a collection.

    9

    EXTEND(n)

    Appends n null elements to a collection.

    10

    EXTEND(n,i)

    Appends n copies of the ith element to a collection.

    11

    TRIM

    Removes one element from the end of a collection.

    12

    TRIM(n)

    Removes n elements from the end of a collection.

    13

    DELETE

    Removes all elements from a collection, setting COUNT to 0.

    14

    DELETE(n)

    Removes the nth element from an associative array with a numeric key or a nested table. If the associative array has a string key, the element corresponding to the key value is deleted. If n is null, DELETE(n) does nothing.

    15

    DELETE(m,n)

    Removes all elements in the range m..n from an associative array or nested table. If m is larger than n or if m or n is null, DELETE(m,n) does nothing.

    Collection Exceptions

    The following table provides the collection exceptions and when they are raised −

    Collection Exception Raised in Situations
    COLLECTION_IS_NULL You try to operate on an atomically null collection.
    NO_DATA_FOUND A subscript designates an element that was deleted, or a nonexistent element of an associative array.
    SUBSCRIPT_BEYOND_COUNT A subscript exceeds the number of elements in a collection.
    SUBSCRIPT_OUTSIDE_LIMIT A subscript is outside the allowed range.
    VALUE_ERROR A subscript is null or not convertible to the key type. This exception might occur if the key is defined as a PLS_INTEGER range, and the subscript is outside this range.

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí PL/SQL – Transactions nhận dự án làm có lương

    PL/SQL – Transactions



    In this chapter, we will discuss the transactions in PL/SQL. A database transaction is an atomic unit of work that may consist of one or more related SQL statements. It is called atomic because the database modifications brought about by the SQL statements that constitute a transaction can collectively be either committed, i.e., made permanent to the database or rolled back (undone) from the database.

    A successfully executed SQL statement and a committed transaction are not same. Even if an SQL statement is executed successfully, unless the transaction containing the statement is committed, it can be rolled back and all changes made by the statement(s) can be undone.

    Starting and Ending a Transaction

    A transaction has a beginning and an end. A transaction starts when one of the following events take place −

    • The first SQL statement is performed after connecting to the database.

    • At each new SQL statement issued after a transaction is completed.

    A transaction ends when one of the following events take place −

    • A COMMIT or a ROLLBACK statement is issued.

    • A DDL statement, such as CREATE TABLE statement, is issued; because in that case a COMMIT is automatically performed.

    • A DCL statement, such as a GRANT statement, is issued; because in that case a COMMIT is automatically performed.

    • User disconnects from the database.

    • User exits from SQL*PLUS by issuing the EXIT command, a COMMIT is automatically performed.

    • SQL*Plus terminates abnormally, a ROLLBACK is automatically performed.

    • A DML statement fails; in that case a ROLLBACK is automatically performed for undoing that DML statement.

    Committing a Transaction

    A transaction is made permanent by issuing the SQL command COMMIT. The general syntax for the COMMIT command is −

    COMMIT;
    

    For example,

    INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
    VALUES (1, ''Ramesh'', 32, ''Ahmedabad'', 2000.00 );
    
    INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
    VALUES (2, ''Khilan'', 25, ''Delhi'', 1500.00 );
    
    INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
    VALUES (3, ''kaushik'', 23, ''Kota'', 2000.00 );
    
    INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
    VALUES (4, ''Chaitali'', 25, ''Mumbai'', 6500.00 );
    
    INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
    VALUES (5, ''Hardik'', 27, ''Bhopal'', 8500.00 );
    
    INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
    VALUES (6, ''Komal'', 22, ''MP'', 4500.00 );
    
    COMMIT;
    

    Rolling Back Transactions

    Changes made to the database without COMMIT could be undone using the ROLLBACK command.

    The general syntax for the ROLLBACK command is −

    ROLLBACK [TO SAVEPOINT < savepoint_name>];
    

    When a transaction is aborted due to some unprecedented situation, like system failure, the entire transaction since a commit is automatically rolled back. If you are not using savepoint, then simply use the following statement to rollback all the changes −

    ROLLBACK;
    

    Savepoints

    Savepoints are sort of markers that help in splitting a long transaction into smaller units by setting some checkpoints. By setting savepoints within a long transaction, you can roll back to a checkpoint if required. This is done by issuing the SAVEPOINT command.

    The general syntax for the SAVEPOINT command is −

    SAVEPOINT < savepoint_name >;
    

    For example

    INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
    VALUES (7, ''Rajnish'', 27, ''HP'', 9500.00 );
    
    INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
    VALUES (8, ''Riddhi'', 21, ''WB'', 4500.00 );
    SAVEPOINT sav1;
    
    UPDATE CUSTOMERS
    SET SALARY = SALARY + 1000;
    ROLLBACK TO sav1;
    
    UPDATE CUSTOMERS
    SET SALARY = SALARY + 1000
    WHERE ID = 7;
    UPDATE CUSTOMERS
    SET SALARY = SALARY + 1000
    WHERE ID = 8;
    
    COMMIT;
    

    ROLLBACK TO sav1 − This statement rolls back all the changes up to the point, where you had marked savepoint sav1.

    After that, the new changes that you make will start.

    Automatic Transaction Control

    To execute a COMMIT automatically whenever an INSERT, UPDATE or DELETE command is executed, you can set the AUTOCOMMIT environment variable as −

    SET AUTOCOMMIT ON;
    

    You can turn-off the auto commit mode using the following command −

    SET AUTOCOMMIT OFF;
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí PL/SQL – Loops nhận dự án làm có lương

    PL/SQL – Loops



    In this chapter, we will discuss Loops in PL/SQL. There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.

    Programming languages provide various control structures that allow for more complicated execution paths.

    A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages −

    Loop Architecture

    PL/SQL provides the following types of loop to handle the looping requirements. Click the following links to check their detail.

    S.No Loop Type & Description
    1

    In this loop structure, sequence of statements is enclosed between the LOOP and the END LOOP statements. At each iteration, the sequence of statements is executed and then control resumes at the top of the loop.

    2

    Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.

    3

    Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.

    4

    You can use one or more loop inside any another basic loop, while, or for loop.

    Labeling a PL/SQL Loop

    PL/SQL loops can be labeled. The label should be enclosed by double angle brackets (<< and >>) and appear at the beginning of the LOOP statement. The label name can also appear at the end of the LOOP statement. You may use the label in the EXIT statement to exit from the loop.

    The following program illustrates the concept −

    DECLARE
       i number(1);
       j number(1);
    BEGIN
       << outer_loop >>
       FOR i IN 1..3 LOOP
          << inner_loop >>
          FOR j IN 1..3 LOOP
             dbms_output.put_line(''i is: ''|| i || '' and j is: '' || j);
          END loop inner_loop;
       END loop outer_loop;
    END;
    /
    

    When the above code is executed at the SQL prompt, it produces the following result −

    i is: 1 and j is: 1
    i is: 1 and j is: 2
    i is: 1 and j is: 3
    i is: 2 and j is: 1
    i is: 2 and j is: 2
    i is: 2 and j is: 3
    i is: 3 and j is: 1
    i is: 3 and j is: 2
    i is: 3 and j is: 3
    
    PL/SQL procedure successfully completed.
    

    The Loop Control Statements

    Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

    PL/SQL supports the following control statements. Labeling loops also help in taking the control outside a loop. Click the following links to check their details.

    S.No Control Statement & Description
    1

    The Exit statement completes the loop and control passes to the statement immediately after the END LOOP.

    2

    Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

    3

    Transfers control to the labeled statement. Though it is not advised to use the GOTO statement in your program.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí PL/SQL – Conditions nhận dự án làm có lương

    PL/SQL – Conditions



    In this chapter, we will discuss conditions in PL/SQL. Decision-making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

    Following is the general form of a typical conditional (i.e., decision making) structure found in most of the programming languages −

    Decision making statements in PL/SQL

    PL/SQL programming language provides following types of decision-making statements. Click the following links to check their detail.

    S.No Statement & Description
    1

    The IF statement associates a condition with a sequence of statements enclosed by the keywords THEN and END IF. If the condition is true, the statements get executed and if the condition is false or NULL then the IF statement does nothing.

    2

    IF statement adds the keyword ELSE followed by an alternative sequence of statement. If the condition is false or NULL, then only the alternative sequence of statements get executed. It ensures that either of the sequence of statements is executed.

    3

    It allows you to choose between several alternatives.

    4

    Like the IF statement, the CASE statement selects one sequence of statements to execute.

    However, to select the sequence, the CASE statement uses a selector rather than multiple Boolean expressions. A selector is an expression whose value is used to select one of several alternatives.

    5

    The searched CASE statement has no selector, and it”s WHEN clauses contain search conditions that yield Boolean values.

    6

    You can use one IF-THEN or IF-THEN-ELSIF statement inside another IF-THEN or IF-THEN-ELSIF statement(s).


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc