0% found this document useful (0 votes)
7 views

Chapter 3_Performing SQL Operation

This document discusses SQL Server transactions, highlighting their properties such as Atomicity, Consistency, Isolation, and Durability (ACID). It explains the use of commands like BEGIN TRANSACTION, COMMIT, and ROLLBACK for managing transactions, along with examples of error handling using TRY...CATCH blocks. Additionally, it covers the concept of cursors in SQL Server, differentiating between implicit and explicit cursors, and the importance of locks for data integrity during concurrent access.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Chapter 3_Performing SQL Operation

This document discusses SQL Server transactions, highlighting their properties such as Atomicity, Consistency, Isolation, and Durability (ACID). It explains the use of commands like BEGIN TRANSACTION, COMMIT, and ROLLBACK for managing transactions, along with examples of error handling using TRY...CATCH blocks. Additionally, it covers the concept of cursors in SQL Server, differentiating between implicit and explicit cursors, and the importance of locks for data integrity during concurrent access.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Advance Database using PL/SQL

Unit 3 : Performing SQL Operations from PL/SQL

SQL Server Transaction


• A transaction is the logical work unit that performs a single activity
or multiple activities in a database.
• Transactions may consist of a single read, write, delete, or update
operations or a combination of these.
• A transaction in SQL Server is a sequential group of statements or
queries to perform single or multiple tasks in a database.
• Each transaction may have single read, write, update, or delete
operations or a combination of all these operations.
• Each transaction must happen two things in SQL Server:
• Either all modification is successful when the transaction is committed.
• Or, all modifications are undone when the transaction is rollback.
Advance Database using PL/SQL
Unit 3 : Performing SQL Operations from PL/SQL

SQL Server Transaction


Advance Database using PL/SQL
Unit 3 : Performing SQL Operations from PL/SQL

SQL Server Transaction


Suppose that, when we want to withdraw money from the ATM, the ATM
application will achieve this operation in three steps.

As a first step, the application will check the balance of the account,
and then it will deduct the money from the source account.
Along with these two processes, it will keep the log of this money withdrawing
activity.
Advance Database using PL/SQL
Unit 3 : Performing SQL Operations from PL/SQL

SQL Server Transaction


The image basically illustrates the working
principle of the transactions in the
relational database systems.
Advance Database using PL/SQL
Unit 3 : Performing SQL Operations from PL/SQL

SQL Server Transaction Properties


• Atomicity: his property ensures that all statements or operations included in the
transaction must be performed successfully. Otherwise, the whole transaction
will be aborted, and all operations are rolled back into their previous state when
any operation is failed..
• Consistency: This property ensures that the database changes state only when a
transaction will be committed successfully. It is also responsible for protecting
data from crashes.
• Isolation: This property guarantees that all transactions are isolated from other
transactions, meaning each operation in the transaction is operated
independently. It also ensures that statements are transparent to each other.
• Durability: This property guarantees that the result of committed transactions
persists in the database permanently even if the system crashes or failed.
Advance Database using PL/SQL
Unit 3 : Performing SQL Operations from PL/SQL

SQL Server Transaction

The transaction properties are referred to as ACID (Atomicity, Consistency, Isolation, Durability) property
Advance Database using PL/SQL
Unit 3 : Performing SQL Operations from PL/SQL

The following are the commands used to control


transactions:

BEGIN TRANSACTION: It is a command that indicates the beginning of each


transaction.

COMMIT: It is a command used to save the changes permanently in the database.

ROLLBACK: It is a command used to cancel all modifications and goes into their
previous state.
Advance Database using PL/SQL
Unit 3 : Performing SQL Operations from PL/SQL

COMMIT
COMMIT in SQL is a transaction control language that is used to
permanently save the changes done in the transaction in
tables/databases. The database cannot regain its previous state after
its execution of commit.

The COMMIT TRANSACTION statement applies the data changes to the database and
the changed data will become permanent.

Syntax:
COMMIT;
Advance Database using PL/SQL
Unit 3 : Performing SQL Operations from PL/SQL

The following example uses the BEGIN TRANSACTION


and COMMIT statements to create a transaction:
use [MYSTORE]
BEGIN TRANSACTION;
INSERT INTO Category (CategoryName,Description) VALUES ('Chocolate', 'Best
Chocolate');
UPDATE Customer set Address='KTM' where CustomerID=4
COMMIT;
or

BEGIN tran t;

INSERT INTO Category (CategoryName,Description) VALUES ('Chocolate', 'Best


Chocolate');
UPDATE Customer set Address='KTM' where CustomerID=4
COMMIT tran t;
Advance Database using PL/SQL
Unit 3 : Performing SQL Operations from PL/SQL

ROLLBACK Command
If any error occurs with any of the SQL grouped statements, all changes need to be aborted. The
process of reversing changes is called rollback.

Syntax for ROLLBACK command:


ROLLBACK;

Example Query

DELETE FROM Student WHERE AGE = 20;


ROLLBACK;
Advance Database using PL/SQL
Unit 3 : Performing SQL Operations from PL/SQL

ROLLBACK Command
begin tran t

declare @SalesPrice float;


set @SalesPrice=1;

insert into Product


(CategoryID,ProductName,CostPrice,SalesPrice,Stock,RewardPoint)
values(1,'television',1000,15000,5,4)

if(@SalesPrice<16000)
begin
print'An SalesPrice less than 16000 is not valid; query is rolled back';
rollback tran t;
end
else
begin
print 'data is inserted'
end
Advance Database using PL/SQL
Unit 3 : Performing SQL Operations from PL/SQL

COMMIT and ROLLBACK Command


BEGIN TRANSACTION
insert into Product
(CategoryID,ProductName,CostPrice,SalesPrice,Stock,RewardPoint)
values(1,Speaker',1000,1500,6,2)

-- Check for error


IF(@@ERROR > 0)
BEGIN
ROLLBACK TRANSACTION
END
ELSE
BEGIN
COMMIT TRANSACTION
END
Advance Database using PL/SQL
Unit 3 : Performing SQL Operations from PL/SQL

COMMIT and ROLLBACK Command


BEGIN TRANSACTION
insert into Product (CategoryID,ProductName,CostPrice,SalesPrice,Stock,RewardPoint)
values(1,'Desktop',7000,14000,5,4)

UPDATE Product SET Stock = 'ten' WHERE ProductName = 'Desktop'


SELECT * FROM Product

COMMIT TRANSACTION

In this output, we can see that the insert statement was executed successfully. However, executing the update
statement found an error due to the data type conversion issue. In this case, the SQL Server does not allow
any changes in the database, which means the insert operation does not add any value, and the select
statement is not executed.
Advance Database using PL/SQL
Unit 3 : Performing SQL Operations from PL/SQL

What is a transaction in SQL Server?


A transaction in SQL Server is a sequence of one or more SQL statements that
are executed as a single unit of work. Transactions ensure the consistency and
integrity of the database by allowing a set of operations to either be fully
completed (committed) or fully undone (rolled back) in case of an error.
s the purpose of the COMMIT statement in SQL Server?
The COMMIT statement is used to permanently save the
changes made during a transaction to the database.
When a COMMIT statement is executed, the changes
become permanent and cannot be undone. It signifies
the successful completion of the transaction.
Advance Database using PL/SQL
Unit 3 : Performing SQL Operations from PL/SQL
How can you handle errors in a transaction in SQL
Server?
In modern SQL Server versions, you can use the
TRY...CATCH blocks to handle errors within a transaction.
The CATCH block allows you to specify actions to be
taken in case of an error, such as rolling back the
s the ROLLBACK statement used in SQL Server?
transaction.
The ROLLBACK statement is used to undo the changes
made during a transaction and revert the database to its
state before the transaction began. It is typically used in
response to an error or to explicitly cancel a transaction.
Advance Database using PL/SQL
Unit 3 : Performing SQL Operations from PL/SQL

Difference between COMMIT and ROLLBACK


COMMIT ROLLBACK
COMMIT permanently saves the changes made by the ROLLBACK undo the changes made by the current
current transaction. transaction.
The transaction can not undo changes after COMMIT
Transaction reaches its previous state after ROLLBACK.
execution.
When the transaction is aborted, incorrect execution,
When the transaction is successful, COMMIT is applied.
system failure ROLLBACK occurs.
In ROLLBACK statement if any operations fail during the
COMMIT statement permanently save the state, when all
completion of a transaction, it cannot permanently save the
the statements are executed successfully without any error.
change and we can undo them using this statement.
Syntax of COMMIT statement are: Syntax of ROLLBACK statement are:
COMMIT; ROLLBACK;
Advance Database using PL/SQL
Unit 3 : Performing SQL Operations from PL/SQL

example of using TRY...CATCH, COMMIT, and


ROLLBACK
BEGIN TRANSACTION;
BEGIN TRY
INSERT INTO Category (CategoryName) VALUES ('Digital Electronics');
INSERT INTO Customer (CustomerName, Address, MobileNo, Email)
VALUES ('John Doe', '123 Main St', '1234567890', '[email protected]');

INSERT INTO Product (CategoryID, ProductName, CostPrice, SalesPrice, Stock,


RewardPoint)
VALUES (10, 'Smartphone', 500.00, 699.99, 50, 10);
COMMIT;
PRINT 'Transaction committed successfully.';
END TRY
BEGIN CATCH
ROLLBACK;
PRINT 'Transaction rolled back due to an error.';
PRINT ERROR_MESSAGE();
END CATCH;
Advance Database using PL/SQL
Unit 3 : Performing SQL Operations from PL/SQL

CURSORS
Cursor is a Temporary Memory or Temporary Work Station. It is Allocated
by Database Server at the Time of Performing DML(Data Manipulation Language)
operations on the Table by the User. Cursors are used to store Database Tables.

There are 2 types of Cursors: Implicit Cursors, and Explicit Cursors.


1.Implicit Cursors: Implicit Cursors are also known as Default Cursors of SQL
SERVER. These Cursors are allocated by SQL SERVER when the user performs DML
operations.
2.Explicit Cursors: Explicit Cursors are Created by Users whenever the user
requires them. Explicit Cursors are used for Fetching data from Table in Row-By-
In SQL Server, a cursor is a database object that allows you to retrieve and manipulate
Row Manner.
rows from a result set one at a time. Cursors are useful when you need to perform
operations on each row of a result set rather than on the set as a whole.
Advance Database using PL/SQL
Unit 3 : Performing SQL Operations from PL/SQL
-- Declare a table variable
DECLARE @Students TABLE (
StudentID INT,
StudentName NVARCHAR(100)
);

-- Insert sample data into the table variable


INSERT INTO @Students (StudentID, StudentName) VALUES (1, 'Alice'), (2, 'Bob'), (3, 'Charlie');

-- Declare variables for cursor


DECLARE @ID INT, @Name NVARCHAR(100);

-- Declare and set up the cursor


DECLARE studentCursor CURSOR FOR SELECT StudentID, StudentName FROM @Students;

-- Open the cursor


OPEN studentCursor;

-- Fetch the first row from the cursor


FETCH NEXT FROM studentCursor INTO @ID, @Name;

-- Loop through the cursor


WHILE @@FETCH_STATUS = 0
BEGIN
-- Perform operations on the current row
PRINT 'Student ID: ' + CAST(@ID AS NVARCHAR(10));
PRINT 'Student Name: ' + @Name;
PRINT '---';
-- Fetch the next row from the cursor
FETCH NEXT FROM studentCursor INTO @ID, @Name;
END
-- Close and deallocate the cursor
CLOSE studentCursor;
DEALLOCATE studentCursor;
Advance Database using PL/SQL
Unit 3 : Performing SQL Operations from PL/SQL

Life Cycle of the cursor


• Declare Variables: Declare variables for each column in the Customer table to store values fetched from the
cursor.
• Declare Cursor: Declare a cursor named customerCursor and define a SELECT statement that retrieves the
desired columns from the Customer table.
• Open Cursor: Open the cursor to start the iteration process.
• Fetch First Row: Use the FETCH NEXT statement to retrieve the first row from the cursor into the declared
variables.
• Loop through Cursor: Use a WHILE loop to iterate through the cursor as long as the @@FETCH_STATUS is 0
(indicating a successful fetch).
• Perform Operations: Perform operations on the current row (in this case, printing information to the
console).
• Close and Deallocate Cursor: Close and deallocate the cursor when done.
Advance Database using PL/SQL
Unit 3 : Performing SQL Operations from PL/SQL

Attributes of Implicit Cursors:


Whenever DML operations such as INSERT, UPDATE, and DELETE are processed in the database,
implicit cursors are generated automatically and used by the framework. These types of cursors are
used for internal processing and can’t be controlled or referred from another code area. Implicit
cursors in SQL just hold the affected rows by the operation and can only refer to the most recent
cursor using the cursor attributes which are shown below.
Advance Database using PL/SQL
Unit 3 : Performing SQL Operations from PL/SQL

Difference between Implicit and Explicit Cursors


Implicit Cursors Explicit Cursors
Implicit cursors are automatically created when select statements are Explicit cursors needs to be defined explicitly by the user by providing a
executed. name.
They are capable of fetching a single row at a time. Explicit cursors can fetch multiple rows.
Closes automatically after execution. Need to close after execution.
They are more vulnerable to errors such as Data errors, etc. They are less vulnerable to errors(Data errors etc.)
Provides less programmatic control to the users User/Programmer has the entire control.
Implicit cursors are less efficient. Comparative to Implicit cursors, explicit cursors are more efficient.
Explicit cursors are defined as:
Implicit Cursors are defined as:
DECLARE
BEGIN
CURSOR cur_name IS
SELECT attr_name from
SELECT attr_name from table_name
table_name
where CONDITION;
where CONDITION;
BEGIN
END
...
Implicit cursors requires anonymous buffer memory for storage purpose. Explicit cursors use user-defined memory space for storage purpose
Advance Database using PL/SQL
Unit 3 : Performing SQL Operations from PL/SQL

What is Lock in SQL Server?


As we all know, multiple users need to access databases concurrently. So locks come into the
picture to prevent data from being corrupted or invalidated when multiple users try to do operations
such as read, write and update on database.

“Lock is defined as a mechanism to ensure data integrity, consistency while allowing concurrent
access to data. It is used to implement concurrency control when multiple users access Database to
manipulate its data at the same time”
Different Models of SQL Server locks
•Shared(S)
• Used for select operations
• Enable other sessions to perform select operations but prevent updates
• read-only operations
• Operation with SELECT statement generally use in Shared mode.

•Exclusive(X)
• Used for DML operations
• Prevents other users from accessing the resource.
• Operations, such as INSERT, UPDATE, or DELETE means DML query. Ensures that multiple updates cannot
be made to the same resource at the same time.
Advance Database using PL/SQL
Unit 3 : Performing SQL Operations from PL/SQL

•Update(U)
• Preliminary stage for exclusive lock. Used by the server when filtering the records to be modified
• Prevents other update locks
• A solution to the cycle deadlock problem

•Intent
• Intent Locks are used for establishing a lock Hierarchy.
• The types of intent locks are:
• intent shared (IS),
• intent exclusive (IX)
• shared with intent exclusive (SIX).
•Schema
• Schema locks are used when an operation dependent on the schema of a table is executing.
• The types of schema locks are:
• Schema modification (Sch-M) and
• Schema stability (Sch-S).

•Bulk Update (BU)


• Bulk Update used when bulk-copying data into a table and the TABLOCK hint is specified. Generally, use
when user want to insert huge data in database/
Advance Database using PL/SQL
Unit 3 : Performing SQL Operations from PL/SQL
-- Declare variables for cursor
DECLARE @CustomerID INT, @CustomerName NVARCHAR(250), @Address NVARCHAR(50), @MobileNo NVARCHAR(12),
@Email NVARCHAR(150);
-- Declare and set up the cursor
DECLARE customerCursor CURSOR FOR SELECT CustomerID, CustomerName, Address, MobileNo, Email FROM
Customer;
-- Open the cursor
OPEN customerCursor;
-- Fetch the first row from the cursor
FETCH NEXT FROM customerCursor INTO @CustomerID, @CustomerName, @Address, @MobileNo, @Email;
-- Loop through the cursor
WHILE @@FETCH_STATUS = 0
BEGIN
-- Perform operations on the current row
PRINT 'Customer ID: ' + CAST(@CustomerID AS NVARCHAR(10));
PRINT 'Customer Name: ' + @CustomerName;
PRINT 'Address: ' + ISNULL(@Address, 'N/A');
PRINT 'Mobile No: ' + ISNULL(@MobileNo, 'N/A');
PRINT 'Email: ' + ISNULL(@Email, 'N/A');
PRINT '---';
-- Fetch the next row from the cursor
FETCH NEXT FROM customerCursor INTO @CustomerID, @CustomerName, @Address, @MobileNo, @Email;
END
-- Close and deallocate the cursor
CLOSE customerCursor;
DEALLOCATE customerCursor;
Advance Database using PL/SQL
Unit 3 : Performing SQL Operations from PL/SQL

Frequently Asked Questions


Q1: Difference between Implicit and Explicit Cursors.
Q2: Describe Attributes of Implicit Cursors.
Q3: What is a transaction in SQL Server? Describe SQL Server Transaction Properties.
Q4: What is the purpose of the COMMIT statement in SQL Server?
Q5: How is the ROLLBACK statement used in SQL Server?
Q6: COMMIT and ROLLBACK Command with example.
Q7: Describe CURSORS and Life Cycle of the cursor.
Q8: What is Lock in SQL Server? Describe Different Models of SQL Server locks.

You might also like