Sql xp 11

72
©NIIT SQL/Lesson 11/Slide 1 of 72 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 Use locks Understand deadlock Declare cursors

description

Old Sql Slides

Transcript of Sql xp 11

Page 1: Sql xp 11

©NIIT SQL/Lesson 11/Slide 1 of 72

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

Use locks

Understand deadlock

Declare cursors

Page 2: Sql xp 11

©NIIT SQL/Lesson 11/Slide 2 of 72

Implementing Transactions and Cursors

Objectives (Contd.)

Open cursors

Fetch data from cursors

Close cursors

Page 3: Sql xp 11

©NIIT SQL/Lesson 11/Slide 3 of 72

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 EmployeeSET cCurrentPosition = '0001'WHERE cEmployeeCode= '000002'UPDATE PositionSET iCurrentStrength=iCurrentStrength + 1WHERE cPositionCode='0001’

Page 4: Sql xp 11

©NIIT SQL/Lesson 11/Slide 4 of 72

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.

Page 5: Sql xp 11

©NIIT SQL/Lesson 11/Slide 5 of 72

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

Page 6: Sql xp 11

©NIIT SQL/Lesson 11/Slide 6 of 72

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

Page 7: Sql xp 11

©NIIT SQL/Lesson 11/Slide 7 of 72

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

Page 8: Sql xp 11

©NIIT SQL/Lesson 11/Slide 8 of 72

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

Page 9: Sql xp 11

©NIIT SQL/Lesson 11/Slide 9 of 72

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

Page 10: Sql xp 11

©NIIT SQL/Lesson 11/Slide 10 of 72

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

Page 11: Sql xp 11

©NIIT SQL/Lesson 11/Slide 11 of 72

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'

Page 12: Sql xp 11

©NIIT SQL/Lesson 11/Slide 12 of 72

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

Page 13: Sql xp 11

©NIIT SQL/Lesson 11/Slide 13 of 72

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'

Page 14: Sql xp 11

©NIIT SQL/Lesson 11/Slide 14 of 72

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.

Page 15: Sql xp 11

©NIIT SQL/Lesson 11/Slide 15 of 72

Implementing Transactions and Cursors

Task List

Identify how to revert the changes made

Execute the transaction

Verify whether the transaction was executed

Page 16: Sql xp 11

©NIIT SQL/Lesson 11/Slide 16 of 72

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

Page 17: Sql xp 11

©NIIT SQL/Lesson 11/Slide 17 of 72

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'

Page 18: Sql xp 11

©NIIT SQL/Lesson 11/Slide 18 of 72

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

Page 19: Sql xp 11

©NIIT SQL/Lesson 11/Slide 19 of 72

Implementing Transactions and Cursors

Execute the transaction (Contd.)

BEGIN

PRINT 'The transaction has been committed.'

COMMIT TRANSACTION

END

Press F5 to execute the transaction

Page 20: Sql xp 11

©NIIT SQL/Lesson 11/Slide 20 of 72

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.

Page 21: Sql xp 11

©NIIT SQL/Lesson 11/Slide 21 of 72

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'

Page 22: Sql xp 11

©NIIT SQL/Lesson 11/Slide 22 of 72

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'

Page 23: Sql xp 11

©NIIT SQL/Lesson 11/Slide 23 of 72

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.

Page 24: Sql xp 11

©NIIT SQL/Lesson 11/Slide 24 of 72

Implementing Transactions and Cursors

Task List

Identify how to break the transaction into parts

Execute the transaction

Verify the execution of the transaction

Page 25: Sql xp 11

©NIIT SQL/Lesson 11/Slide 25 of 72

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

Page 26: Sql xp 11

©NIIT SQL/Lesson 11/Slide 26 of 72

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'

Page 27: Sql xp 11

©NIIT SQL/Lesson 11/Slide 27 of 72

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'

Page 28: Sql xp 11

©NIIT SQL/Lesson 11/Slide 28 of 72

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

Page 29: Sql xp 11

©NIIT SQL/Lesson 11/Slide 29 of 72

Implementing Transactions and Cursors

Execute the transaction (Contd.)

BEGIN

PRINT 'Both the transactions have beencommitted.'

COMMIT TRANSACTION

END

Press F5 to execute the transaction

Page 30: Sql xp 11

©NIIT SQL/Lesson 11/Slide 30 of 72

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.

Page 31: Sql xp 11

©NIIT SQL/Lesson 11/Slide 31 of 72

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'

Page 32: Sql xp 11

©NIIT SQL/Lesson 11/Slide 32 of 72

Implementing Transactions and Cursors

11.D.4 Experiencing the use of Locks (Contd.) While the above transaction is being executed, User2 wants to

schedule an interview for candidates, but is unable to view the details of candidates with more than 80 marks. He/she uses the following statements to view the details and schedule an interview:

BEGIN TRANSACTION

SELECT * from ExternalCandidate

WHERE siTestScore > 80

UPDATE ExternalCandidate

SET dInterviewDate = getdate()+ 2

WHERE siTestScore > 80

Identify why User2 is unable to execute the transaction.

Page 33: Sql xp 11

©NIIT SQL/Lesson 11/Slide 33 of 72

Implementing Transactions and Cursors

Task List

Identify why User2 is unable to execute the transaction

Simulate the two transactions to understand locking

Execute the transaction on Terminal1

Execute the transaction on Terminal2

Execute the command on Terminal1

Verify that the tables were locked when the transaction was in progress

Execute the COMMIT TRANSACTION statement on Terminal2

Page 34: Sql xp 11

©NIIT SQL/Lesson 11/Slide 34 of 72

Implementing Transactions and Cursors

Identify why User2 is unable to execute the transaction

Locking

Ensures transactional integrity and database consistency

Is implemented automatically

Without locking, the view of transaction processing is impossible

Page 35: Sql xp 11

©NIIT SQL/Lesson 11/Slide 35 of 72

Implementing Transactions and Cursors

Identify why User2 is unable to execute the transaction (Contd.)

Transactional Concurrency

SQL Server provides both optimistic and pessimistic concurrency controls

Optimistic Concurrency control

Works on the basis of assumption that resource conflicts between multiple users are unlikely but not impossible

Allows transactions to execute without locking any resources

Resources are checked only when a transaction has to commit

Page 36: Sql xp 11

©NIIT SQL/Lesson 11/Slide 36 of 72

Implementing Transactions and Cursors

Identify why user2 is unable to execute the transaction (Contd.)

Pessimistic Concurrency Control Locks resources for the duration of a transaction

Concurrency Problems

Lost updates

The lost update problem occurs when two or more transactions try to modify the same row that is based on the originally selected value

Uncommitted Dependency

An uncommitted dependency problem is also known as a dirty read problem

Page 37: Sql xp 11

©NIIT SQL/Lesson 11/Slide 37 of 72

Implementing Transactions and Cursors

Identify why User2 is unable to execute the transaction (Contd.)

Inconsistent Analysis

An inconsistent analysis problem is also known as the non-repeatable problem

Phantom Reads

A phantom read is also known as the phantom problem

Page 38: Sql xp 11

©NIIT SQL/Lesson 11/Slide 38 of 72

Implementing Transactions and Cursors

Identify why user2 is unable to execute the transaction (Contd.)

Locking Items - SQL Server can lock the following resources:

RID

Key

Page

Extent

Table

Database

Page 39: Sql xp 11

©NIIT SQL/Lesson 11/Slide 39 of 72

Implementing Transactions and Cursors

Identify why user2 is unable to execute the transaction (Contd.)

SQL Server Lock Modes

Shared Locks

Allow concurrent transactions to read a resource

Update Locks

Prevent a common form of deadlock from occurring

Exclusive Locks

Exclusively restrict concurrent transactions from accessing a resource

Page 40: Sql xp 11

©NIIT SQL/Lesson 11/Slide 40 of 72

Implementing Transactions and Cursors

Identify why User2 is unable to execute the transaction (Contd.)

Intent Locks

Indicates that SQL Server wants to acquire a shared or exclusive lock on some of the resources lower down in the hierarchy

Schema Locks

SQL Server considers schema modification (Sch-M) locks when any data definition language (DDL) operation is being performed on a table

Page 41: Sql xp 11

©NIIT SQL/Lesson 11/Slide 41 of 72

Implementing Transactions and Cursors

Identify why User2 is unable to execute the transaction (Contd.)

Result:

User2 is unable to execute his transaction because SQL Server has locked the ExternalCandidate table as it is being used by User1

Page 42: Sql xp 11

©NIIT SQL/Lesson 11/Slide 42 of 72

Implementing Transactions and Cursors

Simulate the two transactions to understand locking

Action:

To simulate the two transactions, connect to SQL Server from two terminals named Terminal1 and Terminal2

Page 43: Sql xp 11

©NIIT SQL/Lesson 11/Slide 43 of 72

Implementing Transactions and Cursors

Execute the transaction on Terminal1

Action:

In the Query Analyzer window, type:

BEGIN TRANSACTION

UPDATE ExternalCandidate

SET siTestScore = 90

WHERE cCandidateCode = '000002'

UPDATE ExternalCandidate

SET dTestDate = getdate()

WHERE cCandidateCode = '000002'

Press F5 to execute the transaction

Page 44: Sql xp 11

©NIIT SQL/Lesson 11/Slide 44 of 72

Implementing Transactions and Cursors

Execute the transaction on Terminal 2

Action:

In the Query Analyzer window, type:

BEGIN TRANSACTION

SELECT * FROM ExternalCandidate

WHERE siTestScore > 80

  UPDATE ExternalCandidate

SET dInterviewDate = getdate()+ 2

WHERE siTestScore > 80

Press F5 to execute the transaction

Page 45: Sql xp 11

©NIIT SQL/Lesson 11/Slide 45 of 72

Implementing Transactions and Cursors

Execute the command on Terminal 1

Action: In the Query Analyzer window, type:

COMMIT TRANSACTION

Press F5 to execute the statement

Page 46: Sql xp 11

©NIIT SQL/Lesson 11/Slide 46 of 72

Implementing Transactions and Cursors

Verify that the tables were locked when the transaction was in progress

Action:

On Terminal2 the transaction would have waited for the ExternalCandiate table to be unlocked by Terminal1

As soon as the COMMIT TRANSACTION command was given on Terminal1, the transaction on Terminal2 would have proceeded and the latest updates of User1 would be visible

Page 47: Sql xp 11

©NIIT SQL/Lesson 11/Slide 47 of 72

Implementing Transactions and Cursors

Execute the COMMIT TRANSACTION statement on Terminal2

Action:

In the Query Analyzer window, type:

COMMIT TRANSACTION

Press F5 to execute the statement

Page 48: Sql xp 11

©NIIT SQL/Lesson 11/Slide 48 of 72

Implementing Transactions and Cursors

Just a Minute

Which of the concurrency problems does the following refer to:

When two or more transactions try to modify the same row that is based on the originally selected value

When a document is distributed to people that contains information which no longer exists in the original document

Page 49: Sql xp 11

©NIIT SQL/Lesson 11/Slide 49 of 72

Implementing Transactions and Cursors

Deadlock

A deadlock is a situation in which two users (or transactions) have locks on separate objects, and each user is waiting for a lock on the other’s object

DISTRIBUTO R PRO D UCTS

TRANSACTIO N A TRANSACTIO N B

Page 50: Sql xp 11

©NIIT SQL/Lesson 11/Slide 50 of 72

Implementing Transactions and Cursors

Deadlock (Contd.) Setting Deadlock Priority

In order to detect deadlock situations, SQL Server scans for sessions that are waiting for a lock request

SQL Server provides the SET DEADLOCK_PRIORITY command to customize deadlocking

Syntax

SET DEADLOCK_PRIORITY {LOW|NORMAL|@deadlock_var}

Customizing LOCK_TIMEOUT

The SET LOCK_TIMEOUT command can be used to set the maximum time that a statement waits on a blocked resource

Page 51: Sql xp 11

©NIIT SQL/Lesson 11/Slide 51 of 72

Implementing Transactions and Cursors

Deadlock (Contd.) By default, SQL Server does not enforce timeout period

Syntax

SET LOCK_TIMEOUT [timeout_period]

Page 52: Sql xp 11

©NIIT SQL/Lesson 11/Slide 52 of 72

Implementing Transactions and Cursors

Just a Minute...

What is a deadlock? How can you customize deadlocks?

Page 53: Sql xp 11

©NIIT SQL/Lesson 11/Slide 53 of 72

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

Page 54: Sql xp 11

©NIIT SQL/Lesson 11/Slide 54 of 72

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.

Page 55: Sql xp 11

©NIIT SQL/Lesson 11/Slide 55 of 72

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

…………………………………….

…………………………………….

Page 56: Sql xp 11

©NIIT SQL/Lesson 11/Slide 56 of 72

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

Page 57: Sql xp 11

©NIIT SQL/Lesson 11/Slide 57 of 72

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

Page 58: Sql xp 11

©NIIT SQL/Lesson 11/Slide 58 of 72

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

Page 59: Sql xp 11

©NIIT SQL/Lesson 11/Slide 59 of 72

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

Page 60: Sql xp 11

©NIIT SQL/Lesson 11/Slide 60 of 72

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

Page 61: Sql xp 11

©NIIT SQL/Lesson 11/Slide 61 of 72

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

Page 62: Sql xp 11

©NIIT SQL/Lesson 11/Slide 62 of 72

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.

Page 63: Sql xp 11

©NIIT SQL/Lesson 11/Slide 63 of 72

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

Page 64: Sql xp 11

©NIIT SQL/Lesson 11/Slide 64 of 72

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, @DepartmentHeadEND

Page 65: Sql xp 11

©NIIT SQL/Lesson 11/Slide 65 of 72

Implementing Transactions and Cursors

Identify the steps required to create the report (Contd.)

-- Close the cursor

CLOSE curDepartment

-- Deallocate the cursor.

DEALLOCATE curDepartment

Page 66: Sql xp 11

©NIIT SQL/Lesson 11/Slide 66 of 72

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

Page 67: Sql xp 11

©NIIT SQL/Lesson 11/Slide 67 of 72

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

……………………………………..

……………………………………..

Page 68: Sql xp 11

©NIIT SQL/Lesson 11/Slide 68 of 72

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.

Page 69: Sql xp 11

©NIIT SQL/Lesson 11/Slide 69 of 72

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.

SQL Server provides two types of concurrency:

Optimistic concurrency

Pessimistic concurrency

Page 70: Sql xp 11

©NIIT SQL/Lesson 11/Slide 70 of 72

Implementing Transactions and Cursors

Summary (Contd.)

There are four types of concurrency problems:

The lost update problem

The uncommitted dependency problem

The inconsistent analysis problem

The phantom read problem

The level at which an SQL Server transaction is prepared to accept inconsistent data is termed as the isolation level.

Page 71: Sql xp 11

©NIIT SQL/Lesson 11/Slide 71 of 72

Implementing Transactions and Cursors

Summary (Contd.)

The following are the lock modes supported by SQL Server:

Shared

Update

Exclusive

Intent

Schema

A deadlock is a situation in which two users (or transactions) have locks on separate objects and each user is waiting for a lock on the other’s object.

A transaction is a sequence of operations performed together as a single logical unit of work.

Page 72: Sql xp 11

©NIIT SQL/Lesson 11/Slide 72 of 72

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)