Author: alien

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

    Discuss PL/SQL



    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.


    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 – Object Oriented nhận dự án làm có lương

    PL/SQL – Object Oriented



    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 AS OBJECT
    (length number,
     width number,
     member function enlarge( inc number) return rectangle,
     NOT FINAL member procedure display) NOT FINAL
    /
    

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

    Type created.
    

    Creating the base 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;
    END;
    /
    

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

    Type body created.
    

    Creating the child object tabletop

    CREATE OR REPLACE TYPE tabletop UNDER rectangle
    (
       material varchar2(20),
       OVERRIDING member procedure display
    )
    /
    

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

    Type created.
    

    Creating the type body for the child object tabletop

    CREATE OR REPLACE TYPE BODY tabletop AS
    OVERRIDING MEMBER PROCEDURE display IS
    BEGIN
       dbms_output.put_line(''Length: ''|| length);
       dbms_output.put_line(''Width: ''|| width);
       dbms_output.put_line(''Material: ''|| material);
    END display;
    /
    

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

    Type body created.
    

    Using the tabletop object and its member functions −

    DECLARE
       t1 tabletop;
       t2 tabletop;
    BEGIN
       t1:= tabletop(20, 10, ''Wood'');
       t2 := tabletop(50, 30, ''Steel'');
       t1.display;
       t2.display;
    END;
    /
    

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

    Length: 20
    Width: 10
    Material: Wood
    Length: 50
    Width: 30
    Material: Steel
    
    PL/SQL procedure successfully completed.
    

    Abstract Objects in PL/SQL

    The NOT INSTANTIABLE clause allows you to declare an abstract object. You cannot use an abstract object as it is; you will have to create a subtype or child type of such objects to use its functionalities.

    For example,

    CREATE OR REPLACE TYPE rectangle AS OBJECT
    (length number,
     width number,
     NOT INSTANTIABLE NOT FINAL MEMBER PROCEDURE display)
     NOT INSTANTIABLE NOT FINAL
    /
    

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

    Type created.
    

    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 – Questions and Answers nhận dự án làm có lương

    PL/SQL Questions and Answers



    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.

    Questions and Answers
    SN Question/Answers Type
    1

    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

    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

    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

    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.


    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 – Date & Time nhận dự án làm có lương

    PL/SQL – Date & Time



    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.


    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 – DBMS Output nhận dự án làm có lương

    PL/SQL – DBMS Output



    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.
    

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