unit-4 stored procedures & transaction …unit-4 stored procedures & transaction managements...

18
UNIT-4 STORED PROCEDURES & TRANSACTION MANAGEMENTS 4.1 STORED PROCEDURES: A SQL stored procedure is a collection of SQL statements and SQL command logic, which is compiled and stored on the database. A stored procedure in SQL allows us to create SQL queries to be stored and executed on the server. Stored procedures can also be cached and reused. The main purpose of stored procedures to hide direct SQL queries from the code and improve performance of database operations such as select, update, and delete data. Syntax: Delimiter $$ Create Procedure procedure_name(Parameter List) Begin Variable declaration; Executable SQL Statements; End$$ Example 1: Delimiter $$ Create Procedure avg_salary() Begin Select Avg(Salary) from Employee; End$$ 4.1.1 Parameter Passing in Stored procedures: In MySQL, a parameter has one of three modes: IN, OUT, or INOUT. IN Mode: is the default mode. When you define an IN parameter in a stored procedure, the calling program has to pass an argument to the stored procedure. In addition, the value of an IN parameter is protected. It means that even the value of the IN parameter is changed inside the stored procedure, its original value is retained after the stored procedure ends. In other words, the stored procedure only works on the copy of the IN parameter. OUT Mode: the value of an OUT parameter can be changed inside the stored procedure and its new value is passed back to the calling program. Notice that the stored procedure cannot access the initial value of the OUT parameter when it starts. INOUT Mode: an INOUT parameter is a combination of IN and OUT parameters. It means that the calling program may pass the argument, and the stored procedure can modify the INOUT parameter, and pass the new value back to the calling program. Example 2: Delimiter $$ Create Procedure pro_number(IN a Integer) Begin a = a+ 10; End$$ Calling Procedure: Call pro_number(@5);

Upload: others

Post on 25-Sep-2020

22 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: UNIT-4 STORED PROCEDURES & TRANSACTION …UNIT-4 STORED PROCEDURES & TRANSACTION MANAGEMENTS 4.1 STORED PROCEDURES: A SQL stored procedure is a collection of SQL statements and SQL

UNIT-4

STORED PROCEDURES & TRANSACTION MANAGEMENTS

4.1 STORED PROCEDURES: A SQL stored procedure is a collection of SQL statements and SQL command logic, which is compiled and stored on the database. A stored procedure in SQL allows us to create SQL queries to be stored and executed on the server. Stored procedures can also be cached and reused. The main purpose of stored procedures to hide direct SQL queries from the code and improve performance of database operations such as select, update, and delete data. Syntax: Delimiter $$ Create Procedure procedure_name(Parameter List) Begin Variable declaration; Executable SQL Statements; End$$ Example 1: Delimiter $$ Create Procedure avg_salary() Begin Select Avg(Salary) from Employee; End$$

4.1.1 Parameter Passing in Stored procedures: In MySQL, a parameter has one of three modes: IN, OUT, or INOUT.

IN Mode: is the default mode. When you define an IN parameter in a stored procedure, the calling program has to pass an argument to the stored procedure. In addition, the value of an IN parameter is protected. It means that even the value of the IN parameter is changed inside the stored procedure, its original value is retained after the stored procedure ends. In other words, the stored procedure only works on the copy of the IN parameter. OUT Mode: the value of an OUT parameter can be changed inside the stored procedure and its new value is passed back to the calling program. Notice that the stored procedure cannot access the initial value of the OUT parameter when it starts. INOUT Mode: an INOUT parameter is a combination of IN and OUT parameters. It means that the calling program may pass the argument, and the stored procedure can modify the INOUT parameter, and pass the new value back to the calling program.

Example 2: Delimiter $$

Create Procedure pro_number(IN a Integer) Begin a = a+ 10; End$$ Calling Procedure: Call pro_number(@5);

Page 2: UNIT-4 STORED PROCEDURES & TRANSACTION …UNIT-4 STORED PROCEDURES & TRANSACTION MANAGEMENTS 4.1 STORED PROCEDURES: A SQL stored procedure is a collection of SQL statements and SQL

Database Management System Unit-4: Stored Procedures & Transaction Managements

Prepared By: Mr. V. K. Wani 2

To check the Output: Execute Select @a; Will print 5 Because of In Mode Parameter.

Example 3: DELIMITER $$ CREATE PROCEDURE GetOfficeByCountry(IN countryName VARCHAR(255)) BEGIN

SELECT * FROM offices WHERE country = countryName; END $$ DELIMITER ;

Example 4: Delimiter $$

Create Procedure pro_number(OUT a Integer) Begin a = a+ 10; End$$

Calling Procedure: Call pro_number(@5);

To check the Output: Execute Select @a; Will print 15 Because of OUT Mode Parameter.

Example 5: DELIMITER $$ CREATE PROCEDURE set_counter(INOUT count Integer, IN inc Integer) BEGIN

SET count = count + inc; END$$ DELIMITER ;

Calling Procedure: Call set_counter (@10, @5);

To check the Output: Execute Select @count; Will print 15 Because of INOUT Mode Paramete.

4.1.2 MySQL Stored Procedure Advantages: Followings are the advantages of using MySQL Stored Procedures:

1. Increasing the performance of applications stored procedure is compiled and stored in the database. But MySQL implements stored procedures slightly different which helps in increasing the performance of the applications. After compiling a stored procedure, MySQL puts it into a cache. And MySQL maintains its own stored procedure cache for every single connection. If an application uses a stored procedure multiple times in a single connection, the compiled version is used. 2. Fast: MySQL Stored procedures are fast because MySQL server takes some advantage of caching. Another reason for its speed is that it makes the reduction in network traffic. 3. Portable: MySQL Stored procedures are portable because when we write our stored procedure in SQL,It will run on every platform that MySQL runs on, without obliging us to install an additional runtime-environment package or set permissions for program execution in the operating system. 4. Reusable and transparent: Stored procedures expose the database interface to all applications so that developers don’t have to develop functions that are already supported in stored procedures. Hence, we can say that MySQL stored procedures are reusable and transparent.

Page 3: UNIT-4 STORED PROCEDURES & TRANSACTION …UNIT-4 STORED PROCEDURES & TRANSACTION MANAGEMENTS 4.1 STORED PROCEDURES: A SQL stored procedure is a collection of SQL statements and SQL

Database Management System Unit-4: Stored Procedures & Transaction Managements

Prepared By: Mr. V. K. Wani 3

5. Secure: MySQL stored procedures are secure because the database administrator can grant appropriate permissions to applications that access stored procedures in the database without giving any permissions on the underlying database tables. Example: Let's consider a simple database setup. In a human resource information system (HRIS), it is reasonable to assume that there exists a table holding the salary information of each employee. An HR employee should have the right to grab some figures out of this table: total salary, average salary, etc but this employee should not see the detailed salary of each employee as this information will be too sensitive and should only be available to a few.

4.1.3 MySQL Stored Procedure Disadvantages: Followings are the disadvantages of using MySQL Stored Procedures:

1. Memory usage increased: If we use many stored procedures, the memory usage of every connection that is using those stored procedures will increase substantially. 2. Restricted for complex business logic: Actually, stored procedure’s constructs are not designed for developing complex and flexible business logic. 3. Difficult to debug: It is difficult to debug stored procedures. Only a few database management systems allow you to debug stored procedures. Unfortunately, MySQL does not provide facilities for debugging stored procedures. 4. Difficult to maintain: It is not easy to develop and maintain stored procedures. Developing and maintaining stored procedures are often required a specialized skill set that not all application developers possess. 4.2 TRIGGERS IN MYSQL: A SQL trigger is a set of SQL statements stored in the database catalog. A SQL trigger is executed or fired whenever an event associated with a table occurs e.g., insert, update or delete. A SQL trigger is a special type of stored procedure. It is special because it is not called directly like a stored procedure. The main difference between a trigger and a stored procedure is that a trigger is called automatically when a data modification event is made against a table whereas a stored procedure must be called explicitly. Triggers cannot be applied on select statements, are are used for following puposes.

1. Data Integrity 2. To Schedule the task. 3. To audit the change in database.

Syntax: CREATE TRIGGER trigger_name trigger_time trigger_event ON table_name FOR EACH ROW BEGIN

Trigger Statements; END;

Page 4: UNIT-4 STORED PROCEDURES & TRANSACTION …UNIT-4 STORED PROCEDURES & TRANSACTION MANAGEMENTS 4.1 STORED PROCEDURES: A SQL stored procedure is a collection of SQL statements and SQL

Database Management System Unit-4: Stored Procedures & Transaction Managements

Prepared By: Mr. V. K. Wani 4

4.2.1 Triggers Attributes: Following are the attributes to triggers 1. Trigger Name: Name of the trigger you want to create. 2. Trigger Time: Trigger time can be either Before or After which indicates the trigger will be executed either before or after the occurrence of event. 3. Trigger Event: It indicates the event on which occurrence trigger will execute. Possible events are INSERT, UPDATE & DELETE. 4. Table Name: Table on which trigger want to set. 5. FOR EACH ROW: This parameter is optional which indicates the trigger will be executed for change in a each row of table.

Example 1: CREATE TRIGGER Employee_trigger After Insert ON Employee FOR EACH ROW BEGIN

Insert into Emp_log values (‘Insert’, Now(), NULL, new.eID); END;

After This the log of this event will be stored in table Emp_log and it will record any insert operation in Employee table. Consider we are inserting a row in Employee table as follow.

Insert into Employee values (5, ‘Utkarsh’, 50000);

After this operation log will be created in Emp_log table as

Event Date & Time Old_Emp_ID New_Emp_ID Insert 2019-04-13 :03:10:00 NULL 5

Similar trigger can be designed for Update and Delete operations also. 4.2.2 Advantages of using SQL triggers SQL triggers provide an alternative way to check the integrity of data. SQL triggers can catch errors in business logic in the database layer. SQL triggers provide an alternative way to run scheduled tasks. By using SQL triggers, you don’t have to wait to run the scheduled tasks because the triggers are invoked automatically before or after a change is made to the data in the tables. SQL triggers are very useful to audit the changes of data in tables.

4.2.3 Disadvantages of using SQL triggers SQL triggers only can provide an extended validation and they cannot replace all the validations. Some simple validations have to be done in the application layer. SQL triggers are invoked and executed invisible from the client applications, therefore, it is difficult to figure out what happens in the database layer. SQL triggers may increase the overhead of the database server. 4.3 CURSORS IN MY SQL: A cursor allows you to iterate a set of rows returned by a query and process each row accordingly. MySQL cursor is read-only, non-scrollable and a sensitive. Read-only because you cannot update data in the underlying table through the cursor.

Page 5: UNIT-4 STORED PROCEDURES & TRANSACTION …UNIT-4 STORED PROCEDURES & TRANSACTION MANAGEMENTS 4.1 STORED PROCEDURES: A SQL stored procedure is a collection of SQL statements and SQL

Database Management System Unit-4: Stored Procedures & Transaction Managements

Prepared By: Mr. V. K. Wani 5

A cursor is an object that provides programmatic access to the result set returned by your SELECT statement. Use a cursor to iterate through the rows in the result set and take action for each row individually. A cursor is a pointer to this context area. Currently, MySQL only allows us to fetch each row in the result set from first to last as determined by the SELECT statement. We cannot fetch from the last to first row, and cannot jump directly to a specific row in the result set. When working with MySQL cursor, you must also declare a NOT FOUND handler to handle the situation when the cursor could not find any row. Because each time you call the FETCH statement, the cursor attempts to read the next row in the result set. When the cursor reaches the end of the result set, it will not be able to get the data, and a condition is raised. The handler is used to handle this condition.

4.3.1 There are two types of cursors Implicit cursors Explicit cursors

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

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

Page 6: UNIT-4 STORED PROCEDURES & TRANSACTION …UNIT-4 STORED PROCEDURES & TRANSACTION MANAGEMENTS 4.1 STORED PROCEDURES: A SQL stored procedure is a collection of SQL statements and SQL

Database Management System Unit-4: Stored Procedures & Transaction Managements

Prepared By: Mr. V. K. Wani 6

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

Working with an explicit cursor includes the following steps:

1. Declaring the Cursor: Declaring the cursor defines the cursor with a name and the associated SELECT statement which will initialize the memory. 2. 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 − 3. 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 4. Closing the Cursor: Closing the cursor means releasing the allocated memory. For example, we will close the above-opened cursor as follows

Example: Delimiter $$ Create Procedure Cursor_Demo() Begin

Declare V_Ename Varchar(20); Declare V_ESalary Integer; Declare V_Finished Integer default 0; // Declaring Cursor Declare c1 Cursor for Select ename, salary from Emplyee; Declare Continue Handler for NOT FOUND set V_Finished=1; Open c1; // Opening Cursor Get_emp : Loop

// Fetching Cursor Fetch c1 into VEname, V_ESalary;

If V_Finished=1 then Leave Get_emp; End if; Select Concat(V_Ename, V_ESalary); End Loop Get_emp; Close c1; // Closing Cursor

End $$ 4.4 AN ASSERTION: An assertion is satisfied if and only if the specified <search condition> is not false. Assertions are similar to check constraints, but unlike check constraints they are not defined on table or column level but are defined on schema level.

Page 7: UNIT-4 STORED PROCEDURES & TRANSACTION …UNIT-4 STORED PROCEDURES & TRANSACTION MANAGEMENTS 4.1 STORED PROCEDURES: A SQL stored procedure is a collection of SQL statements and SQL

Database Management System Unit-4: Stored Procedures & Transaction Managements

Prepared By: Mr. V. K. Wani 7

Assertions are similar to check constraints, but unlike check constraints they are not defined on table or column level but are defined on schema level. CREATE ASSERTION <constraint name> CHECK (<search condition>)

4.5 EMBEDDED & DYNAMIC SQL 4.5.1 Embedded SQL: Embedded SQL is a method of combining the computing power of a programming language and the database manipulation capabilities of SQL. Embedded SQL statements are SQL statements written inline with the program source code , of the host language. The gap between application programs and SQL is bridged by the use of embedded SQL and dynamic SQLs. These SQLs provide the utility to use SQLs inside the application language like C, C++, Java etc, and make these applications to communicate with DB. Hence when user submits a request or enters values in the form, he gets the result what he is requested. Embedded SQL is the one which combines the high level language with the DB language like SQL. It allows the application languages to communicate with DB and get requested result. The high level languages which supports embedding SQLs within it are also known as host language. There are different host languages which support embedding SQL within it like C, C++, ADA, Pascal, FORTRAN, Java etc. In Embedded SQL how the data will be accessed is predetermined at compile time.

Embedded SQL Program Development: Embedded SQL is a mixture of SQL and programming language, so it cannot be fed directly to a general purpose programming language compiler. The execution is a multi-step which is as follows.

1. First the embedded SQL source code is fed to the SQL pre-compiler. The pre-compiler scans the program and processes the embedded SQL statements present in the code. There can be different pre-compilers for different type of programming languages. 2. After processing the source code, the pre-compiler produces files as its output. The first file contains the source program without embedded SQL statements and the second file contains all the embedded SQL statements used in the program. 3. The first file produced by pre-compiler that contains the source program is fed to the compiler for the host programming. The compiler processes the source code and produces object code as its output. 4. Now the linker takes the object modules produced by the compiler and link them with various library routines and produces an executable program. 5. The database request modules, produced by the pre-compiler are submitted to a special BIND program. The BIND program examines the SQL statements, parse them, validates them, optimizes them and finally produces an application plan for each statement. The result is a combined application plan for the entire program, that represents a DBMS-executable version of its embedded SQL statements. The BIND program stores the plan in the database, usually assigning it the name of the application program that has created it.

Page 8: UNIT-4 STORED PROCEDURES & TRANSACTION …UNIT-4 STORED PROCEDURES & TRANSACTION MANAGEMENTS 4.1 STORED PROCEDURES: A SQL stored procedure is a collection of SQL statements and SQL

Database Management System Unit-4: Stored Procedures & Transaction Managements

Prepared By: Mr. V. K. Wani 8

Figure: Steps of Execution in Embedded SQL

4.5.2. What is Dynamic SQL: When the pattern of database access is known in advance then static SQL is very adequate to serve us. Sometimes, in many applications we may not know the pattern of database access in advance. For example, a report writer must be able to decide at run time that which SQL statements will be needed to access the database. Such a need can’t be fulfilled with static SQL and requires an advanced form of static SQL known as dynamic SQL. Definition: In dynamic SQL, the SQL statements are not hard coded in the programming language. The text of the SQL statement is asked at the run time to the user. In dynamic SQL, the SQL statements that are to be executed are not known until runtime, so DBMS can’t get prepared for executing the statements in advanced. When the program is executed, the DBMS takes the text of SQL statements to execute the statements that are executed in such a manner called statement string. Once DBMS receives the text, it goes through a five steps execution as illustrated below.

Dynamic Statement Execution: The Execute Immediate statement provides the simplest form of dynamic SQL. This statement passes the text of SQL statements to DBMS and asks the DBMS to execute the SQL statements immediately. For using the statement our program goes through the following steps. 1. The program constructs a SQL statement as a string of text in one of its data areas called a buffer. 2. The program passes the SQL statements to the DBMS with the EXECUTE IMMEDIATE statement. 3. The DBMS executes the statement and sets the SQL CODE/SQL STATE values to flag the finishing status same like if the statement had been hard coded using static SQL.

Page 9: UNIT-4 STORED PROCEDURES & TRANSACTION …UNIT-4 STORED PROCEDURES & TRANSACTION MANAGEMENTS 4.1 STORED PROCEDURES: A SQL stored procedure is a collection of SQL statements and SQL

Database Management System Unit-4: Stored Procedures & Transaction Managements

Prepared By: Mr. V. K. Wani 9

4.5.3 Comparisons of Embedded Vs Dynamic SQL

STATIC (EMBEDDED) SQL DYNAMIC (INTERACTIVE) SQL In Static SQL, how database will be accessed is predetermined in the embedded SQL statement.

In Dynamic SQL, how database will be accessed is determined at run time.

It is more swift and efficient. It is less swift and efficient. SQL statements are compiled at compile time. SQL statements are compiled at run time.

Parsing, Validation, Optimization and Generation of application plan are done at compile time.

Parsing, Validation, Optimization and Generation of application plan are done at run time.

It is generally used for situations where data is distributed uniformly.

It is generally used for situations where data is distributed non uniformly.

EXECUTE IMMEDIATE, EXECUTE and PREPARE statements are not used.

EXECUTE IMMEDIATE, EXECUTE and PREPARE statements are used.

It is less flexible. It is more flexible. 4.6 TRANSACTIONS A transaction can be defined as a group of tasks. A single task is the minimum processing unit which cannot be divided further. Or A transaction is a single logical unit of work which accesses and possibly modifies the contents of a database. Transactions access data using read and write operations. All types of database access operation which are held between the beginning and end transaction statements are considered as a single logical transaction. During the transaction the database is inconsistent. Only once the database is committed the state is changed from one consistent state to another.

Page 10: UNIT-4 STORED PROCEDURES & TRANSACTION …UNIT-4 STORED PROCEDURES & TRANSACTION MANAGEMENTS 4.1 STORED PROCEDURES: A SQL stored procedure is a collection of SQL statements and SQL

Database Management System Unit-4: Stored Procedures & Transaction Managements

Prepared By: Mr. V. K. Wani 10

4.6.1 ACID Properties of transactions: A transaction is a very small unit of a program and it may contain several low level tasks. A transaction in a database system must maintain Atomicity, Consistency, Isolation, and Durability commonly known as ACID properties in order to ensure accuracy, completeness, and data integrity. Atomicity: This property states that a transaction must be treated as an atomic unit, that is, either all of its operations are executed or none. There must be no state in a database where a transaction is left partially completed. States should be defined either before the execution of the transaction or after the execution/abortion/failure of the transaction. Consistency: The database must remain in a consistent state after any transaction. No transaction should have any adverse effect on the data residing in the database. If the database was in a consistent state before the execution of a transaction, it must remain consistent after the execution of the transaction as well. Durability : The database should be durable enough to hold all its latest updates even if the system fails or restarts. If a transaction updates a chunk of data in a database and commits, then the database will hold the modified data. If a transaction commits but the system fails before the data could be written on to the disk, then that data will be updated once the system springs back into action. Isolation : In a database system where more than one transaction are being executed simultaneously and in parallel, the property of isolation states that all the transactions will be carried out and executed as if it is the only transaction in the system. No transaction will affect the existence of any other transaction. 4.6.2 States of Transactions / Transaction Management

Figure: States of Transactions Active: In this state, the transaction is being executed. This is the initial state of every transaction. The transaction will remains in active state till the all sub unit or operations of transactions are executing. From Active state transaction may enter in to either failed or partially committed state. Partially Committed: Till the transactions are executing in active state it uses local memory or buffer for execution. The reason is that if transaction is partially executed then it will result in inconsistency into database. So When a transaction executes its final operation or complete its execution in active state and now is ready to update in database then it enters in to partially committed state.

Failed: A transaction is said to be in a failed state if any of the checks made by the database recovery system fails. A failed transaction can no longer proceed further. A transaction can enter in failed state from active state if it is partially executed in active state.

Page 11: UNIT-4 STORED PROCEDURES & TRANSACTION …UNIT-4 STORED PROCEDURES & TRANSACTION MANAGEMENTS 4.1 STORED PROCEDURES: A SQL stored procedure is a collection of SQL statements and SQL

Database Management System Unit-4: Stored Procedures & Transaction Managements

Prepared By: Mr. V. K. Wani 11

Or it may enter in failed state from partially committed state if transaction failed to update the transaction in database.

Aborted: If any of the checks fails and the transaction has reached a failed state, then the recovery manager rolls back all its write operations on the local memory to bring it back to its original state where it was prior to the execution of the transaction, i.e. the contents related to transaction in local memory are erased. Transactions in this state are called aborted.

Committed: If a transaction executes all its operations successfully and the changes are successfully updated and committed in database from local memory then , it is said to be committed state. All its effects are now permanently established on the database system. After successful commit the local memory content will be erased.

Terminated: Transaction will be terminated if it is completed successfully or it is aborted. 4.7 CONCEPTS OF SCHEDULE: A chronological execution sequence of a transaction is called a schedule. A schedule can have many transactions in it, each comprising of a number of instructions/tasks. Or A series of operation from one transaction to another transaction is known as schedule. It is used to preserve the order of the operation in each of the individual transaction. The different types of schedules are shown in following diagram.

Figure: Types of Schedule

4.7.1 Types of Schedules 1. Serial Schedule: It is a schedule in which transactions are aligned in such a way that one transaction is executed first. When the first transaction completes its cycle, then the next transaction is executed. Transactions are ordered one after the other. This type of schedule is called a serial schedule, as transactions are executed in a serial manner. In a multi-transaction environment, serial schedules are considered as a benchmark. The execution sequence of an instruction in a transaction cannot be changed, but two transactions

Page 12: UNIT-4 STORED PROCEDURES & TRANSACTION …UNIT-4 STORED PROCEDURES & TRANSACTION MANAGEMENTS 4.1 STORED PROCEDURES: A SQL stored procedure is a collection of SQL statements and SQL

Database Management System Unit-4: Stored Procedures & Transaction Managements

Prepared By: Mr. V. K. Wani 12

can have their instructions executed in a random fashion. This execution does no harm if two transactions are mutually independent and working on different segments of data; but in case these two transactions are working on the same data, then the results may vary. This ever-varying result may bring the database to an inconsistent state.

To resolve this problem, we allow parallel execution of a transaction schedule, if its transactions are either serializable or have some equivalence relation among them. For example: Suppose there are two transactions T1 and T2 which have some operations. If it has no interleaving of operations, then there are the following two possible outcomes:

1. Execute all the operations of T1 which was followed by all the operations of T2. 2. Execute all the operations of T2 which was followed by all the operations of T1. o In the given (a) figure, Schedule A shows the serial schedule where T1 followed by T2. o In the given (b) figure, Schedule B shows the serial schedule where T2 followed by T1.

Figure . (A) Figure . (B)

2: Non-serial Schedule: If interleaving of operations is allowed, then there will be non-serial schedule. It contains many possible orders in which the system can execute the individual operations of the transactions. In the given figure (c) and (d), Schedule C and Schedule D are the non-serial schedules. It has interleaving of operations.

Figure .(C) Figure . (D)

Types of Non-serial Schedule: Serializable & Non Serializable Schedule A. Serializable schedule: A schedule is called serializable whenever executing the transactions sequentially, in some order, could have left the database in the same state as the actual schedule, i.e. concurrency is not affected by the transaction. The serializability of schedules is used to find non-serial schedules that allow the transaction to execute concurrently without interfering with one another. It identifies which schedules are correct

Page 13: UNIT-4 STORED PROCEDURES & TRANSACTION …UNIT-4 STORED PROCEDURES & TRANSACTION MANAGEMENTS 4.1 STORED PROCEDURES: A SQL stored procedure is a collection of SQL statements and SQL

Database Management System Unit-4: Stored Procedures & Transaction Managements

Prepared By: Mr. V. K. Wani 13

when executions of the transaction have interleaving of their operations. A non-serial schedule will be serializable if its result is equal to the result of its transactions executed serially. Figure E Shows the serializable Schedules.

Figure (E). Types of Serializable schedule: Conflict Serializable & View Serializable A1. Conflict Serializable: A schedule is called conflict serializable if it can be transformed into a serial schedule by swapping non-conflicting operations. Conflicting operations: Two operations are said to be conflicting if all conditions satisfy: They belong to different transactions They operate on the same data item At Least one of them is a write operation

Figure: S1 = S2. Means it is non-conflict. Figure: S1! = S2. Means it is conflict.

A2. View Serializability: A schedule will view serializable if it is view equivalent to a serial schedule. If a schedule is conflict serializable, then it will be view serializable. The view serializable which does not conflict serializable contains blind writes.

View Equivalent: Two schedules S1 and S2 are said to be view equivalent if they satisfy the following conditions: 1. Initial Read: An initial read of both schedules must be the same. Suppose two schedule S1 and S2. In schedule S1, if a transaction T1 is reading the data item A, then in S2, transaction T1 should also read A.

Page 14: UNIT-4 STORED PROCEDURES & TRANSACTION …UNIT-4 STORED PROCEDURES & TRANSACTION MANAGEMENTS 4.1 STORED PROCEDURES: A SQL stored procedure is a collection of SQL statements and SQL

Database Management System Unit-4: Stored Procedures & Transaction Managements

Prepared By: Mr. V. K. Wani 14

Above two schedules are view equivalent because Initial read operation in S1 is done by T1 and in S2 it is also done by T1. 2. Updated Read: In schedule S1, if Ti is reading A which is updated by Tj then in S2 also, Ti should read A which is updated by Tj.

Above two schedules are not view equal because, in S1, T3 is reading A updated by T2 and in S2, T3 is reading A updated by T1. 3. Final Write: A final write must be the same between both the schedules. In schedule S1, if a transaction T1 updates A at last then in S2, final writes operations should also be done by T1.

Above two schedules is view equal because Final write operation in S1 is done by T3 and in S2, the final write operation is also done by T3. Example:

B. Non-Serializable Schedules: A non-serial schedule which is not serializable is called as a non-serializable schedule. A non-serializable schedule is not guaranteed to produce the the same effect as produced by some serial schedule on any consistent database. These schedules may or may not be consistent and may or may not be recoverable. Figure F Shows the non serializable Schedules.

Page 15: UNIT-4 STORED PROCEDURES & TRANSACTION …UNIT-4 STORED PROCEDURES & TRANSACTION MANAGEMENTS 4.1 STORED PROCEDURES: A SQL stored procedure is a collection of SQL statements and SQL

Database Management System Unit-4: Stored Procedures & Transaction Managements

Prepared By: Mr. V. K. Wani 15

Figure. (F).

B1. Recoverable Schedules: If in a schedule, A transaction performs a dirty read operation from an uncommitted transaction And its commit operation is delayed till the uncommitted transaction either commits or roll backs then such a schedule is known as a Recoverable Schedule. Here, The commit operation of the transaction that performs the dirty read is delayed. This ensures that it still has a chance to recover if the uncommitted transaction fails later. Example: Consider the following schedule-

Here, T2 performs a dirty read operation. The commit operation of T2 is delayed till T1 commits or roll backs. T1 commits later. T2 is now allowed to commit. In case, T1 would have failed, T2 has a chance to recover by rolling back.

Types of Recoverable schedule: Cascading , Cascadeless & Strict RecoverableSchedules

B1.1 Cascading Abort : If in a schedule, failure of one transaction causes several other dependent transactions to rollback or abort, then such a schedule is called as a Cascading Schedule or Cascading Rollback or Cascading Abort. It simply leads to the wastage of CPU

Page 16: UNIT-4 STORED PROCEDURES & TRANSACTION …UNIT-4 STORED PROCEDURES & TRANSACTION MANAGEMENTS 4.1 STORED PROCEDURES: A SQL stored procedure is a collection of SQL statements and SQL

Database Management System Unit-4: Stored Procedures & Transaction Managements

Prepared By: Mr. V. K. Wani 16

time. If transaction T1 abort as T2 read data that written by T1 which is not committed. Hence it’s cascading rollback.

Here,

Transaction T2 depends on T1. Transaction T3 depends on T2.

In this schedule,

The failure of T1 causes the T2 to rollback.

The rollback of T2 causes the T3 to rollback.

Such a rollback is called as a Cascading Rollback.

B1.2 Cascadeless Schedule: If in a schedule, a transaction is not allowed to read a data item until the last transaction that has written it is committed or aborted, then such a schedule is called as a Cascadeless Schedule. In other words, Cascadeless schedule allows only committed read operations. Therefore, it avoids cascading roll back and thus saves CPU time. However, it allows uncommitted write operations. Example:

B1.3 Strict Schedule: A schedule is called strict if every value written by a transaction $T$ is not read or changed by other transactions until T either aborts or commits. Strict schedules avoid cascading aborts. Every serial schedule is strict, but serializable schedules may or may not be strict, avoid cascading aborts or recoverable! Example:

Page 17: UNIT-4 STORED PROCEDURES & TRANSACTION …UNIT-4 STORED PROCEDURES & TRANSACTION MANAGEMENTS 4.1 STORED PROCEDURES: A SQL stored procedure is a collection of SQL statements and SQL

Database Management System Unit-4: Stored Procedures & Transaction Managements

Prepared By: Mr. V. K. Wani 17

Note That Strict schedules are more strict

than cascadeless schedules. All strict schedules are

cascadeless schedules. All cascadeless schedules are not

strict schedules.

B2. Irrecoverable Schedules: If in a schedule, A transaction performs a dirty read operation from an uncommitted transaction And commits before the transaction from which it has read the value then such a schedule is known as an Irrecoverable Schedule. Example: Consider the following schedule.

Here, T2 performs a dirty read operation. T2 commits before T1. T1 fails later and roll backs. The value that T2 read now stands to be incorrect.

Page 18: UNIT-4 STORED PROCEDURES & TRANSACTION …UNIT-4 STORED PROCEDURES & TRANSACTION MANAGEMENTS 4.1 STORED PROCEDURES: A SQL stored procedure is a collection of SQL statements and SQL

Database Management System Unit-4: Stored Procedures & Transaction Managements

Prepared By: Mr. V. K. Wani 18

T2 can not recover since it has already committed.

Serializability: When multiple transactions are being executed by the operating system in a multiprogramming environment, there are possibilities that instructions of one transactions are interleaved with some other transaction. Equivalence Schedules: An equivalence schedule can be of the following types 1. Result Equivalence: If two schedules produce the same result after execution, they are said to be result equivalent. They may yield the same result for some value and different results for another set of values. That's why this equivalence is not generally considered significant. 2. View Equivalence: Two schedules would be view equivalence if the transactions in both the schedules perform similar actions in a similar manner. For example :

If T reads the initial data in S1, then it also reads the initial data in S2. If T reads the value written by J in S1, then it also reads the value written by J in S2. If T performs the final write on the data value in S1, then it also performs the final

write on the data value in S2. 3. Conflict Equivalence: Two schedules would be conflicting if they have the following properties

Both belong to separate transactions. Both accesses the same data item. At least one of them is "write" operation.

Two schedules having multiple transactions with conflicting operations are said to be conflict equivalent if and only if −

Both the schedules contain the same set of Transactions. The order of conflicting pairs of operation is maintained in both the schedules.

Note − View equivalent schedules are view serializable and conflict equivalent schedules are conflict serializable. All conflict serializable schedules are view serializable too.