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

SQL XP 11

SQL SERVER presentation

Uploaded by

parimengal039
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

SQL XP 11

SQL SERVER presentation

Uploaded by

parimengal039
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 49

Implementing Transactions and Cursors

Objectives
 In this lesson, you will learn to:
Create a transaction
Commit a transaction
Rollback a transaction
Rollback part of a transaction
Declare cursors
Implementing Transactions and Cursors

Objectives (Contd.)
Open cursors
Fetch data from cursors
Close cursors
Implementing Transactions and Cursors

11.D.1 Ensuring Data Consistency


 An internal candidate with the employee code ‘000002’ has
been selected for the position of ‘Sales Manager’ (position
code=‘0001’). This has to be updated in the Employee table.
In addition, the current strength of positions filled also needs
to be updated in the Position table.
 The update statement to do the above is as follows:
UPDATE Employee
SET cCurrentPosition = '0001'
WHERE cEmployeeCode= '000002'
UPDATE Position
SET iCurrentStrength=iCurrentStrength + 1
WHERE cPositionCode='0001’
Implementing Transactions and Cursors

11.D.1 Ensuring Data Consistency (Contd.)


 A system crash due to any reason between the two updates
would result in data inconsistency. This needs to be
prevented. To prevent this, ensure that either both updates
happen or neither happens.
Implementing Transactions and Cursors

Task List
 Identify how to prevent inconsistency in data
 Execute the transaction
 Verify that the data has been updated in both tables
Implementing Transactions and Cursors

Identify how to prevent inconsistency in data


Transactions
 A transaction can be defined as a sequence of operations
performed together as a single logical unit of work
 A single unit of work must possess the four properties
called ACID (Atomicity, Consistency, Isolation, and
Durability).
Atomicity

Consistency

Isolation

Durability
Implementing Transactions and Cursors

Identify how to prevent inconsistency in data (Contd.)


 To fulfill the requirements of the ACID properties, SQL Server
provides the following features:
 Transaction management
 Locking
 Logging
 Transaction log - is the log maintained by SQL Server to
manage all its transactions
 Explicit transaction - is one in which both the start and the end
of the transaction are defined explicitly
Implementing Transactions and Cursors

Identify how to prevent inconsistency in data (Contd.)


 BEGIN TRANSACTION: This statement marks the start of
an explicit transaction
 Syntax
BEGIN TRAN[SACTION] [transaction_name |
@tran_name_variable]
 COMMIT TRANSACTION or COMMIT WORK: This marks
the ending point of an explicit transaction
 Syntax
COMMIT [TRAN[SACTION][transaction_name |
@tran_name_variable]]
Implementing Transactions and Cursors

Identify how to prevent inconsistency in data (Contd.)


 Autocommit transactions
 The autocommit mode is the default transaction
management mode of SQL Server
 Result:
 The use of transactions can prevent inconsistent data
 The UPDATE statements can be made atomic by using
the BEGIN TRANSACTION and COMMIT
TRANSACTION statements
Implementing Transactions and Cursors

Execute the transaction


 Action:
 In the Query Analyzer window, type:
BEGIN TRANSACTION trnUpdatePosition
UPDATE Employee
SET cCurrentPosition = '0001'
WHERE cEmployeeCode= '000002'
UPDATE Position
SET iCurrentStrength = iCurrentStrength + 1
WHERE cPositionCode = '0001'
COMMIT TRANSACTION trnUpdatePosition
 Press F5 to execute the statements
Implementing Transactions and Cursors

Verify that the data has been updated in both the


tables
 Action:
 Execute the following SELECT statements to verify that
the rows have been updated:
SELECT * FROM Position
WHERE cPositionCode = '0001'
SELECT * FROM Employee

WHERE cEmployeeCode = '000002'


Implementing Transactions and Cursors

Just a Minute
 Identify the following properties of a single unit of work:
 Any data modification made by concurrent transactions
must be isolated from the modifications made by other
concurrent transactions
 All the data modifications are performed or none of them
are performed
 Any change in data by a completed transaction remains
permanently in effect in the system
 All data is in a consistent state after a transaction is
completed successfully
Implementing Transactions and Cursors

11.D.2 Reverting Changes


 Ten candidates have been recruited for the position 0015.
To reflect this change, the siNoOfVacancy attribute of the
Requisition table is to be decreased by 10 for
cRequisitionCode 000004. Also the iCurrentStrength
attribute of the Position table is to be increased by 10 for
cPositionCode 0015 using the following commands:
UPDATE Requisition
set siNoOfVacancy=siNoOfVacancy - 10
WHERE cRequisitionCode='000004'
Implementing Transactions and Cursors

11.D.2 Reverting Changes (Contd.)


UPDATE Position
set iCurrentStrength=iCurrentStrength + 10
WHERE cPositionCode='0015’
 Both these statements should be atomic and if the
iCurrentStrength attribute becomes more than the
iBudgetedStrength attribute, then the changes made by the
UPDATE statements must be reverted.
Implementing Transactions and Cursors

Task List
 Identify how to revert the changes made
 Execute the transaction
 Verify whether the transaction was executed
Implementing Transactions and Cursors

Identify how to revert the changes made


 ROLLBACK TRANSACTION or ROLLBACK WORK: These
statements roll back an explicit or implicit transaction to the
beginning of the transaction, or to a save-point within a
transaction
 Syntax
ROLLBACK [TRAN[SACTION] [transaction_name
|@tran_name_variable |savepoint_name |
@savepoint_variable]]
 Result
 A transaction can be reverted using the ROLLBACK
TRANSACTION statement
Implementing Transactions and Cursors

Execute the transaction


 Action:
 In the Query Analyzer window, type:
BEGIN TRANSACTION
UPDATE Requisition
SET siNoOfVacancy=siNoOfVacancy - 10
WHERE cRequisitionCode='000004'

UPDATE Position
SET iCurrentStrength=iCurrentStrength + 10
WHERE cPositionCode='0015'
Implementing Transactions and Cursors

Execute the transaction (Contd.)


IF (SELECT iBudgetedStrength-iCurrentStrength
FROM Position WHERE cPositionCode = '0015')
<0
BEGIN
PRINT 'Current strength cannot be more
than budgeted strength. Transaction has not
been committed.'
ROLLBACK TRANSACTION
END
ELSE
Implementing Transactions and Cursors

Execute the transaction (Contd.)


BEGIN
PRINT 'The transaction has been
committed.'
COMMIT TRANSACTION
END
 Press F5 to execute the transaction
Implementing Transactions and Cursors

Verify whether the transaction was executed


 Action:
 View the output displayed in the result window.

If the difference between iBudgetedStrength and


iCurrentStrength is less than zero for PositionCode
'0015', the transaction is rolled back and 'Current strength
cannot be more than budgeted strength. Transaction has
not been committed.' is displayed. Otherwise, the
transaction is committed and the appropriate message is
displayed.
Implementing Transactions and Cursors

11.D.3 Reverting Part of a Transaction


 The Employee and the Position tables need to be updated
using the following transaction:
Transaction 1:
UPDATE Employee

SET cCurrentPosition = '0015'


WHERE cEmployeeCode = '000002'
UPDATE Position
SET iCurrentStrength = iCurrentStrength + 1
WHERE cPositionCode = '0015'
Implementing Transactions and Cursors

11.D.3 Reverting Part of a Transaction (Contd.)


 The Requisition and the Position tables need to be updated
using the following transaction:
Transaction 2:
UPDATE Requisition
SET siNoOfVacancy=siNoOfVacancy - 10
WHERE cRequisitionCode='000004'
UPDATE Position
SET iCurrentStrength=iCurrentStrength + 10
WHERE cPositionCode='0015'
Implementing Transactions and Cursors

11.D.3 Reverting Part of a Transaction (Contd.)


 All the updates should be done together. If the value of
iCurrentStrength becomes more than iBudgetedStrength for
cPositionCode 0015, the changes made by the second
transaction must be reverted but the changes made by the
first transaction should be allowed.
Implementing Transactions and Cursors

Task List
 Identify how to break the transaction into parts
 Execute the transaction
 Verify the execution of the transaction
Implementing Transactions and Cursors

Identify how to break the transaction into parts


 SAVE TRANSACTION
 It sets a save-point within a transaction. A save-point
divides a transaction into logical units so that the
transaction can return to the save point, if a part of the
transaction is conditionally canceled.
 Syntax
SAVE TRAN[SACTION] {savepoint_name |
@savepoint_variable}
 Result
 The transaction can be broken into logical units using
SAVE TRANSACTION statement
Implementing Transactions and Cursors

Execute the transaction


 Action:
 In the Query Analyzer window, type:
BEGIN TRANSACTION
UPDATE Employee
SET cCurrentPosition = '0015'
WHERE cEmployeeCode = '000002'
UPDATE Position
SET iCurrentStrength = iCurrentStrength + 1
WHERE cPositionCode = '0015'
Implementing Transactions and Cursors

Execute the transaction (Contd.)


SAVE TRANSACTION trnTransaction1

UPDATE Requisition
SET siNoOfVacancy=siNoOfVacancy - 10
WHERE cRequisitionCode='000004'
UPDATE Position
SET iCurrentStrength=iCurrentStrength+10
WHERE cPositionCode='0015'
Implementing Transactions and Cursors

Execute the transaction (Contd.)


IF (SELECT iBudgetedStrength-
iCurrentStrength FROM Position WHERE
cPositionCode = '0015') <0
BEGIN
PRINT 'Transaction 1 has been committed

but transaction 2 has not been committed.'


ROLLBACK TRANSACTION trnTransaction1
END
ELSE
Implementing Transactions and Cursors

Execute the transaction (Contd.)


BEGIN
PRINT 'Both the transactions have been
committed.'
COMMIT TRANSACTION
END
Press F5 to execute the transaction
Implementing Transactions and Cursors

Verify the execution of the transaction


 Action:
 View the output being displayed in the result window.

If the difference between iBudgetedStrength and


iCurrentStrength is less than zero for PositionCode
'0015', transaction 1 is committed but transaction 2 is not
committed. Otherwise, both the transactions are
committed. Appropriate messages are displayed in both
the cases.
Implementing Transactions and Cursors

11.D.4 Experiencing the use of Locks


 User1 has given the following statements to update the details in
the ExternalCandidate table with the test score and the test date
after a candidate with cCandidateCode ‘000002’ has taken the
test.
BEGIN TRANSACTION
UPDATE ExternalCandidate
SET siTestScore = 90
WHERE cCandidateCode='000002'
UPDATE ExternalCandidate
SET dTestDate = getdate()
WHERE cCandidateCode = '000002'
Implementing Transactions and Cursors

Cursors
 A cursor is a database object that helps in accessing and
manipulating data in a given result set
 Cursors enable the processing of rows in the result set in the
following ways:
 Allow specific rows to be retrieved from the result set
 Allow the current row in the result set to be modified
 Help navigate from the current row in the result set to a
different row
 Allow data modified by other users to be visible in the
result set
Implementing Transactions and Cursors

Structure of Cursors
 The following tasks need to be performed while using a
cursor in SQL Server:
 The cursor needs to be defined and its attributes need to
be set.
 The cursor needs to be opened.
 The required rows need to be fetched from the cursor.
 The data in the current row of the cursor can be modified,
if required.
 The cursor needs to be closed.
 The cursor should be deallocated. This is a good practice
as resources used by the cursor are released.
Implementing Transactions and Cursors

11.D.5 Displaying Specific Attributes as Variables


 You need to call a meeting of all department heads. For this
you need a list of departments and the corresponding
department heads as per the following format:
Department Name = Production
Department Head = Samuel Moore
Department Name = Sales
Department Head = Donald Fleming
…………………………………….
…………………………………….
Implementing Transactions and Cursors

Task List
 Identify the steps required to create the report
 Execute the statements required to create the report
 Verify that the output is as per the required results
Implementing Transactions and Cursors

Identify the steps required to create the report


 Declaring Cursors
 You can define a cursor and its characteristics set by using
the DECLARE CURSOR statement
 Syntax
DECLARE cursor_name [INSENSITIVE] [SCROLL]
CURSOR FOR {select_statement}
[FOR {READ ONLY | UPDATE [OF column_list]}]
Implementing Transactions and Cursors

Identify the steps required to create the report


(Contd.)
 Opening Cursors
 You can open a previously declared cursor by using the
OPEN statement
 Syntax
OPEN cursor_name
Implementing Transactions and Cursors

Identify the steps required to create the report


(Contd.)
 Fetching Data
 After opening the cursor, you can retrieve a specific row
from the result set of the cursor. SQL Server 2000
provides the FETCH statement to accomplish this task.
 Syntax
FETCH [[NEXT | PRIOR | FIRST | LAST |
ABSOLUTE n | RELATIVE n]] FROM cursor_name[
INTO @variable_name [ ,...n ] ]
Implementing Transactions and Cursors

Identify the steps required to create the report


(Contd.)
 Closing Cursors
 You must close a cursor in order to release the resources
held by it. A cursor can be closed with the CLOSE
statement.
 Syntax

CLOSE cursor_name
Implementing Transactions and Cursors

Identify the steps required to create the report


(Contd.)
 Deallocate Cursors
 A cursor can be deallocated using the DEALLOCATE
statement
 Syntax
DEALLOCATE cursor_name
Implementing Transactions and Cursors

Identify the steps required to create the report


(Contd.)
 Result:
 You need to use the following statements to display the
report.
--Create two variables that would store the
--values returned by the fetch statement.
DECLARE @DepartmentName char(25)
DECLARE @DepartmentHead char(25)
-- Defines the cursor that can be used to
-- access the records of the table,row by
--row.
Implementing Transactions and Cursors

Identify the steps required to create the report


(Contd.)
DECLARE curDepartment cursor for
SELECT vDepartmentName,vDepartmentHead FROM
Department
-- Open the cursor
OPEN curDepartment
-- Fetch the rows into variables
FETCH curDepartment into @DepartmentName,
@DepartmentHead
Implementing Transactions and Cursors

Identify the steps required to create the report


(Contd.)
-- Start a loop to display all the rows of
-- the cursor.
While (@@fetch_status = 0)
BEGIN
Print 'Department Name = ' +
@DepartmentName
Print 'Department Head = ' +
@DepartmentHead
-- Fetch the next row from the cursor.
FETCH curDepartment into @DepartmentName,
@DepartmentHead
END
Implementing Transactions and Cursors

Identify the steps required to create the report


(Contd.)
-- Close the cursor
CLOSE curDepartment
-- Deallocate the cursor.
DEALLOCATE curDepartment
Implementing Transactions and Cursors

Execute the statements required to create the report


 Action:
 In the Query Analyzer window, type steps required to
display the report
 Press F5 to execute the statements
Implementing Transactions and Cursors

Verify that the output is as per the required results


 Action:
 Check whether the Department Name and Department
Head are displayed as follows:
Department Name = Production
Department Head = Samuel Moore
Department Name = Sales
Department Head = Donald Fleming
……………………………………..
……………………………………..
Implementing Transactions and Cursors

Summary
In this lesson, you learned that:
 A transaction is created using the BEGIN TRANSACTION
statement.
 A transaction can be committed by issuing the COMMIT
TRANSACTION statement.
 A transaction can be rolled back by issuing the ROLLBACK
TRANSACTION statement.
 A transaction can be partially rolled back by saving part of it
by issuing the SAVE TRANSACTION statement.
Implementing Transactions and Cursors

Summary (Contd.)
 A transaction can be created inside a stored procedure. The
BEGIN TRANSACTION, COMMIT TRANSACTION, and
ROLLBACK TRANSACTION form the SQL statements of the
procedure.
 SQL Server uses the concept of locking to ensure
transactional integrity and database consistency.
Implementing Transactions and Cursors

Summary (Contd.)
 All successful distributed transactions follow the two-phase
commit mode.
 A cursor is a database object that helps in accessing and
manipulating row-by-row data in a given result set.
 Cursors are implemented in the following sequence:
 Declaring the cursor (DECLARE statement)
 Opening the cursor (OPEN statement)
 Fetching the row (FETCH statement)
 Closing the cursor (CLOSE statement)
 Releasing the cursor (DEALLOCATE statement)

You might also like