SlideShare a Scribd company logo
1 of 72
Download to read offline
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


©NIIT                                  SQL/Lesson 11/Slide 1 of 72
Implementing Transactions and Cursors

Objectives (Contd.)
    Open cursors
    Fetch data from cursors
    Close cursors




©NIIT                              SQL/Lesson 11/Slide 2 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 Employee
   SET cCurrentPosition = '0001'
   WHERE cEmployeeCode= '000002'
   UPDATE Position
   SET iCurrentStrength=iCurrentStrength + 1
   WHERE cPositionCode='0001’

©NIIT                                         SQL/Lesson 11/Slide 3 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.




©NIIT                                      SQL/Lesson 11/Slide 4 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




©NIIT                                       SQL/Lesson 11/Slide 5 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

©NIIT                                        SQL/Lesson 11/Slide 6 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


©NIIT                                         SQL/Lesson 11/Slide 7 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]]

©NIIT                                  SQL/Lesson 11/Slide 8 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




©NIIT                                       SQL/Lesson 11/Slide 9 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


©NIIT                                      SQL/Lesson 11/Slide 10 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'


©NIIT                                      SQL/Lesson 11/Slide 11 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

©NIIT                                          SQL/Lesson 11/Slide 12 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'



©NIIT                                        SQL/Lesson 11/Slide 13 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.




©NIIT                                    SQL/Lesson 11/Slide 14 of 72
Implementing Transactions and Cursors

Task List
 Identify how to revert the changes made
 Execute the transaction
 Verify whether the transaction was executed




©NIIT                                       SQL/Lesson 11/Slide 15 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

©NIIT                                         SQL/Lesson 11/Slide 16 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'
©NIIT                                       SQL/Lesson 11/Slide 17 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

©NIIT                              SQL/Lesson 11/Slide 18 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




©NIIT                                       SQL/Lesson 11/Slide 19 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.



©NIIT                                          SQL/Lesson 11/Slide 20 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'

©NIIT                                    SQL/Lesson 11/Slide 21 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'


©NIIT                                     SQL/Lesson 11/Slide 22 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.




©NIIT                                   SQL/Lesson 11/Slide 23 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




©NIIT                                       SQL/Lesson 11/Slide 24 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
©NIIT                                         SQL/Lesson 11/Slide 25 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'
©NIIT                                       SQL/Lesson 11/Slide 26 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'


©NIIT                              SQL/Lesson 11/Slide 27 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


©NIIT                              SQL/Lesson 11/Slide 28 of 72
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




©NIIT                                      SQL/Lesson 11/Slide 29 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.




©NIIT                                          SQL/Lesson 11/Slide 30 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'
©NIIT                                       SQL/Lesson 11/Slide 31 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.
©NIIT                                       SQL/Lesson 11/Slide 32 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

©NIIT                                      SQL/Lesson 11/Slide 33 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




©NIIT                                       SQL/Lesson 11/Slide 34 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
 ©NIIT
              to commit                       SQL/Lesson 11/Slide 35 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
©NIIT                                           SQL/Lesson 11/Slide 36 of 72
Implementing Transactions and Cursors

Identify why User2 is unable to execute the transaction
(Contd.)
     Inconsistent Analysis
        ® Aninconsistent analysis problem is also known as the
         non-repeatable problem
     Phantom Reads
        ®A   phantom read is also known as the phantom problem




©NIIT                                      SQL/Lesson 11/Slide 37 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



©NIIT                                     SQL/Lesson 11/Slide 38 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


©NIIT                                         SQL/Lesson 11/Slide 39 of 72
Implementing Transactions and Cursors

Identify why User2 is unable to execute the transaction
(Contd.)
     Intent Locks
        ® Indicatesthat 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



©NIIT                                      SQL/Lesson 11/Slide 40 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




©NIIT                                     SQL/Lesson 11/Slide 41 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




©NIIT                                      SQL/Lesson 11/Slide 42 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

©NIIT                                       SQL/Lesson 11/Slide 43 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


©NIIT                                       SQL/Lesson 11/Slide 44 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




©NIIT                                      SQL/Lesson 11/Slide 45 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




©NIIT                                      SQL/Lesson 11/Slide 46 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




©NIIT                                       SQL/Lesson 11/Slide 47 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




©NIIT                                      SQL/Lesson 11/Slide 48 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

           T R A N S A C T IO N A      T R A N S A C T IO N B


               D IS T R IB U T O R           PRO DUCTS




©NIIT                                           SQL/Lesson 11/Slide 49 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
©NIIT                                      SQL/Lesson 11/Slide 50 of 72
Implementing Transactions and Cursors

Deadlock (Contd.)
     By default, SQL Server does not enforce timeout period
     Syntax
        SET LOCK_TIMEOUT [timeout_period]




©NIIT                                      SQL/Lesson 11/Slide 51 of 72
Implementing Transactions and Cursors

Just a Minute...
 What is a deadlock? How can you customize deadlocks?




©NIIT                                  SQL/Lesson 11/Slide 52 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


©NIIT                                        SQL/Lesson 11/Slide 53 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.
©NIIT                                       SQL/Lesson 11/Slide 54 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
  …………………………………….
  …………………………………….

©NIIT                                      SQL/Lesson 11/Slide 55 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




©NIIT                                        SQL/Lesson 11/Slide 56 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]}]




©NIIT                                       SQL/Lesson 11/Slide 57 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




©NIIT                                     SQL/Lesson 11/Slide 58 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 ] ]



©NIIT                                       SQL/Lesson 11/Slide 59 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




©NIIT                                      SQL/Lesson 11/Slide 60 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




©NIIT                                   SQL/Lesson 11/Slide 61 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.
©NIIT                                      SQL/Lesson 11/Slide 62 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


©NIIT                                  SQL/Lesson 11/Slide 63 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, @DepartmentHead
    END
©NIIT                                  SQL/Lesson 11/Slide 64 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




©NIIT                                  SQL/Lesson 11/Slide 65 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




©NIIT                                      SQL/Lesson 11/Slide 66 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
        ……………………………………..
        ……………………………………..



©NIIT                                      SQL/Lesson 11/Slide 67 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.



©NIIT                                        SQL/Lesson 11/Slide 68 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



©NIIT                                     SQL/Lesson 11/Slide 69 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.




©NIIT                                     SQL/Lesson 11/Slide 70 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.
©NIIT                                       SQL/Lesson 11/Slide 71 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)

©NIIT                                       SQL/Lesson 11/Slide 72 of 72

More Related Content

Viewers also liked

Comp tia n+_session_08
Comp tia n+_session_08Comp tia n+_session_08
Comp tia n+_session_08Niit Care
 
01 iec t1_s1_plt_session_01
01 iec t1_s1_plt_session_0101 iec t1_s1_plt_session_01
01 iec t1_s1_plt_session_01Niit Care
 
Ms sql server architecture
Ms sql server architectureMs sql server architecture
Ms sql server architectureAjeet Singh
 

Viewers also liked (8)

Dacj 1-3 b
Dacj 1-3 bDacj 1-3 b
Dacj 1-3 b
 
Comp tia n+_session_08
Comp tia n+_session_08Comp tia n+_session_08
Comp tia n+_session_08
 
01 iec t1_s1_plt_session_01
01 iec t1_s1_plt_session_0101 iec t1_s1_plt_session_01
01 iec t1_s1_plt_session_01
 
SQL | Computer Science
SQL | Computer ScienceSQL | Computer Science
SQL | Computer Science
 
MS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTUREMS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTURE
 
Sql server basics
Sql server basicsSql server basics
Sql server basics
 
Ajs 1 b
Ajs 1 bAjs 1 b
Ajs 1 b
 
Ms sql server architecture
Ms sql server architectureMs sql server architecture
Ms sql server architecture
 

Similar to Sql xp 11

1_Transaction.pdf
1_Transaction.pdf1_Transaction.pdf
1_Transaction.pdfNhtHong96
 
Wcf Transaction Handling
Wcf Transaction HandlingWcf Transaction Handling
Wcf Transaction HandlingGaurav Arora
 
Customizing Change Management
Customizing Change ManagementCustomizing Change Management
Customizing Change ManagementAras
 
PROCEDURE FOR MONTH END DAY 1 INCLUDING SCREEN SHOT & SCRIPTS (Final rev 090211)
PROCEDURE FOR MONTH END DAY 1 INCLUDING SCREEN SHOT & SCRIPTS (Final rev 090211)PROCEDURE FOR MONTH END DAY 1 INCLUDING SCREEN SHOT & SCRIPTS (Final rev 090211)
PROCEDURE FOR MONTH END DAY 1 INCLUDING SCREEN SHOT & SCRIPTS (Final rev 090211)Shakil Zaman
 
SQL Server Transaction Management
SQL Server Transaction ManagementSQL Server Transaction Management
SQL Server Transaction ManagementDenise McInerney
 
Scm lsmw steps_onweb
Scm lsmw steps_onwebScm lsmw steps_onweb
Scm lsmw steps_onwebHarsha Reddy
 
CA Cloud Service Management: Configuring Change Management
CA Cloud Service Management: Configuring Change ManagementCA Cloud Service Management: Configuring Change Management
CA Cloud Service Management: Configuring Change ManagementCA Technologies
 
10 qmds2005 session14
10 qmds2005 session1410 qmds2005 session14
10 qmds2005 session14Niit Care
 
Restoration and-concurrency-database
Restoration and-concurrency-databaseRestoration and-concurrency-database
Restoration and-concurrency-databaseraima sen
 
385125794-SAP-New-Asset-Accounting-Training-Document17-26-pdf.pdf
385125794-SAP-New-Asset-Accounting-Training-Document17-26-pdf.pdf385125794-SAP-New-Asset-Accounting-Training-Document17-26-pdf.pdf
385125794-SAP-New-Asset-Accounting-Training-Document17-26-pdf.pdfssuserad3af4
 
Deep Dive into Oracle ADF Transactions
Deep Dive into Oracle ADF TransactionsDeep Dive into Oracle ADF Transactions
Deep Dive into Oracle ADF TransactionsEugene Fedorenko
 
IBM Streams V4.1 and Incremental Checkpointing
IBM Streams V4.1 and Incremental CheckpointingIBM Streams V4.1 and Incremental Checkpointing
IBM Streams V4.1 and Incremental Checkpointinglisanl
 
208-dataflowdgm_5.ppt
208-dataflowdgm_5.ppt208-dataflowdgm_5.ppt
208-dataflowdgm_5.pptTalhaNazeer5
 
208-dataflowdgm.ppt
208-dataflowdgm.ppt208-dataflowdgm.ppt
208-dataflowdgm.pptRAJA RAY
 
data flow diagram power point presentation
data flow diagram power point presentationdata flow diagram power point presentation
data flow diagram power point presentationSUBHASHREEBASU5
 
Spring Transaction Management
Spring Transaction ManagementSpring Transaction Management
Spring Transaction ManagementYe Win
 

Similar to Sql xp 11 (20)

1_Transaction.pdf
1_Transaction.pdf1_Transaction.pdf
1_Transaction.pdf
 
Transaction
TransactionTransaction
Transaction
 
Wcf Transaction Handling
Wcf Transaction HandlingWcf Transaction Handling
Wcf Transaction Handling
 
Customizing Change Management
Customizing Change ManagementCustomizing Change Management
Customizing Change Management
 
MySQL Transactions
MySQL TransactionsMySQL Transactions
MySQL Transactions
 
PROCEDURE FOR MONTH END DAY 1 INCLUDING SCREEN SHOT & SCRIPTS (Final rev 090211)
PROCEDURE FOR MONTH END DAY 1 INCLUDING SCREEN SHOT & SCRIPTS (Final rev 090211)PROCEDURE FOR MONTH END DAY 1 INCLUDING SCREEN SHOT & SCRIPTS (Final rev 090211)
PROCEDURE FOR MONTH END DAY 1 INCLUDING SCREEN SHOT & SCRIPTS (Final rev 090211)
 
SQL Server Transaction Management
SQL Server Transaction ManagementSQL Server Transaction Management
SQL Server Transaction Management
 
Scm lsmw steps_onweb
Scm lsmw steps_onwebScm lsmw steps_onweb
Scm lsmw steps_onweb
 
CH09.ppt
CH09.pptCH09.ppt
CH09.ppt
 
CA Cloud Service Management: Configuring Change Management
CA Cloud Service Management: Configuring Change ManagementCA Cloud Service Management: Configuring Change Management
CA Cloud Service Management: Configuring Change Management
 
10 qmds2005 session14
10 qmds2005 session1410 qmds2005 session14
10 qmds2005 session14
 
Restoration and-concurrency-database
Restoration and-concurrency-databaseRestoration and-concurrency-database
Restoration and-concurrency-database
 
385125794-SAP-New-Asset-Accounting-Training-Document17-26-pdf.pdf
385125794-SAP-New-Asset-Accounting-Training-Document17-26-pdf.pdf385125794-SAP-New-Asset-Accounting-Training-Document17-26-pdf.pdf
385125794-SAP-New-Asset-Accounting-Training-Document17-26-pdf.pdf
 
Deep Dive into Oracle ADF Transactions
Deep Dive into Oracle ADF TransactionsDeep Dive into Oracle ADF Transactions
Deep Dive into Oracle ADF Transactions
 
Less09 Data
Less09 DataLess09 Data
Less09 Data
 
IBM Streams V4.1 and Incremental Checkpointing
IBM Streams V4.1 and Incremental CheckpointingIBM Streams V4.1 and Incremental Checkpointing
IBM Streams V4.1 and Incremental Checkpointing
 
208-dataflowdgm_5.ppt
208-dataflowdgm_5.ppt208-dataflowdgm_5.ppt
208-dataflowdgm_5.ppt
 
208-dataflowdgm.ppt
208-dataflowdgm.ppt208-dataflowdgm.ppt
208-dataflowdgm.ppt
 
data flow diagram power point presentation
data flow diagram power point presentationdata flow diagram power point presentation
data flow diagram power point presentation
 
Spring Transaction Management
Spring Transaction ManagementSpring Transaction Management
Spring Transaction Management
 

More from Niit Care (20)

Ajs 4 b
Ajs 4 bAjs 4 b
Ajs 4 b
 
Ajs 4 a
Ajs 4 aAjs 4 a
Ajs 4 a
 
Ajs 4 c
Ajs 4 cAjs 4 c
Ajs 4 c
 
Ajs 3 b
Ajs 3 bAjs 3 b
Ajs 3 b
 
Ajs 3 a
Ajs 3 aAjs 3 a
Ajs 3 a
 
Ajs 3 c
Ajs 3 cAjs 3 c
Ajs 3 c
 
Ajs 2 b
Ajs 2 bAjs 2 b
Ajs 2 b
 
Ajs 2 a
Ajs 2 aAjs 2 a
Ajs 2 a
 
Ajs 2 c
Ajs 2 cAjs 2 c
Ajs 2 c
 
Ajs 1 a
Ajs 1 aAjs 1 a
Ajs 1 a
 
Ajs 1 c
Ajs 1 cAjs 1 c
Ajs 1 c
 
Dacj 4 2-c
Dacj 4 2-cDacj 4 2-c
Dacj 4 2-c
 
Dacj 4 2-b
Dacj 4 2-bDacj 4 2-b
Dacj 4 2-b
 
Dacj 4 2-a
Dacj 4 2-aDacj 4 2-a
Dacj 4 2-a
 
Dacj 4 1-c
Dacj 4 1-cDacj 4 1-c
Dacj 4 1-c
 
Dacj 4 1-b
Dacj 4 1-bDacj 4 1-b
Dacj 4 1-b
 
Dacj 4 1-a
Dacj 4 1-aDacj 4 1-a
Dacj 4 1-a
 
Dacj 1-2 b
Dacj 1-2 bDacj 1-2 b
Dacj 1-2 b
 
Dacj 1-3 c
Dacj 1-3 cDacj 1-3 c
Dacj 1-3 c
 
Dacj 1-3 a
Dacj 1-3 aDacj 1-3 a
Dacj 1-3 a
 

Recently uploaded

Dynamical Context introduction word sensibility orientation
Dynamical Context introduction word sensibility orientationDynamical Context introduction word sensibility orientation
Dynamical Context introduction word sensibility orientationBuild Intuit
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...BookNet Canada
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsYoss Cohen
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxAna-Maria Mihalceanu
 
Digital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentDigital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentMahmoud Rabie
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessWSO2
 
Laying the Data Foundations for Artificial Intelligence!
Laying the Data Foundations for Artificial Intelligence!Laying the Data Foundations for Artificial Intelligence!
Laying the Data Foundations for Artificial Intelligence!Memoori
 
Transcript: Green paths: Learning from publishers’ sustainability journeys - ...
Transcript: Green paths: Learning from publishers’ sustainability journeys - ...Transcript: Green paths: Learning from publishers’ sustainability journeys - ...
Transcript: Green paths: Learning from publishers’ sustainability journeys - ...BookNet Canada
 
Automation Ops Series: Session 3 - Solutions management
Automation Ops Series: Session 3 - Solutions managementAutomation Ops Series: Session 3 - Solutions management
Automation Ops Series: Session 3 - Solutions managementDianaGray10
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Women in Automation 2024: Career session - explore career paths in automation
Women in Automation 2024: Career session - explore career paths in automationWomen in Automation 2024: Career session - explore career paths in automation
Women in Automation 2024: Career session - explore career paths in automationDianaGray10
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Introduction-to-Wazuh-and-its-integration.pptx
Introduction-to-Wazuh-and-its-integration.pptxIntroduction-to-Wazuh-and-its-integration.pptx
Introduction-to-Wazuh-and-its-integration.pptxmprakaash5
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFMichael Gough
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Mark Simos
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 

Recently uploaded (20)

Dynamical Context introduction word sensibility orientation
Dynamical Context introduction word sensibility orientationDynamical Context introduction word sensibility orientation
Dynamical Context introduction word sensibility orientation
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platforms
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance Toolbox
 
Digital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentDigital Tools & AI in Career Development
Digital Tools & AI in Career Development
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with Platformless
 
Laying the Data Foundations for Artificial Intelligence!
Laying the Data Foundations for Artificial Intelligence!Laying the Data Foundations for Artificial Intelligence!
Laying the Data Foundations for Artificial Intelligence!
 
Transcript: Green paths: Learning from publishers’ sustainability journeys - ...
Transcript: Green paths: Learning from publishers’ sustainability journeys - ...Transcript: Green paths: Learning from publishers’ sustainability journeys - ...
Transcript: Green paths: Learning from publishers’ sustainability journeys - ...
 
Automation Ops Series: Session 3 - Solutions management
Automation Ops Series: Session 3 - Solutions managementAutomation Ops Series: Session 3 - Solutions management
Automation Ops Series: Session 3 - Solutions management
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Women in Automation 2024: Career session - explore career paths in automation
Women in Automation 2024: Career session - explore career paths in automationWomen in Automation 2024: Career session - explore career paths in automation
Women in Automation 2024: Career session - explore career paths in automation
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Introduction-to-Wazuh-and-its-integration.pptx
Introduction-to-Wazuh-and-its-integration.pptxIntroduction-to-Wazuh-and-its-integration.pptx
Introduction-to-Wazuh-and-its-integration.pptx
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDF
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 

Sql xp 11

  • 1. 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 ©NIIT SQL/Lesson 11/Slide 1 of 72
  • 2. Implementing Transactions and Cursors Objectives (Contd.) Open cursors Fetch data from cursors Close cursors ©NIIT SQL/Lesson 11/Slide 2 of 72
  • 3. 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’ ©NIIT SQL/Lesson 11/Slide 3 of 72
  • 4. 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. ©NIIT SQL/Lesson 11/Slide 4 of 72
  • 5. 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 ©NIIT SQL/Lesson 11/Slide 5 of 72
  • 6. 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 ©NIIT SQL/Lesson 11/Slide 6 of 72
  • 7. 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 ©NIIT SQL/Lesson 11/Slide 7 of 72
  • 8. 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]] ©NIIT SQL/Lesson 11/Slide 8 of 72
  • 9. 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 ©NIIT SQL/Lesson 11/Slide 9 of 72
  • 10. 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 ©NIIT SQL/Lesson 11/Slide 10 of 72
  • 11. 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' ©NIIT SQL/Lesson 11/Slide 11 of 72
  • 12. 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 ©NIIT SQL/Lesson 11/Slide 12 of 72
  • 13. 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' ©NIIT SQL/Lesson 11/Slide 13 of 72
  • 14. 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. ©NIIT SQL/Lesson 11/Slide 14 of 72
  • 15. Implementing Transactions and Cursors Task List Identify how to revert the changes made Execute the transaction Verify whether the transaction was executed ©NIIT SQL/Lesson 11/Slide 15 of 72
  • 16. 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 ©NIIT SQL/Lesson 11/Slide 16 of 72
  • 17. 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' ©NIIT SQL/Lesson 11/Slide 17 of 72
  • 18. 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 ©NIIT SQL/Lesson 11/Slide 18 of 72
  • 19. Implementing Transactions and Cursors Execute the transaction (Contd.) BEGIN PRINT 'The transaction has been committed.' COMMIT TRANSACTION END Press F5 to execute the transaction ©NIIT SQL/Lesson 11/Slide 19 of 72
  • 20. 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. ©NIIT SQL/Lesson 11/Slide 20 of 72
  • 21. 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' ©NIIT SQL/Lesson 11/Slide 21 of 72
  • 22. 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' ©NIIT SQL/Lesson 11/Slide 22 of 72
  • 23. 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. ©NIIT SQL/Lesson 11/Slide 23 of 72
  • 24. Implementing Transactions and Cursors Task List Identify how to break the transaction into parts Execute the transaction Verify the execution of the transaction ©NIIT SQL/Lesson 11/Slide 24 of 72
  • 25. 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 ©NIIT SQL/Lesson 11/Slide 25 of 72
  • 26. 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' ©NIIT SQL/Lesson 11/Slide 26 of 72
  • 27. 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' ©NIIT SQL/Lesson 11/Slide 27 of 72
  • 28. 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 ©NIIT SQL/Lesson 11/Slide 28 of 72
  • 29. 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 ©NIIT SQL/Lesson 11/Slide 29 of 72
  • 30. 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. ©NIIT SQL/Lesson 11/Slide 30 of 72
  • 31. 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' ©NIIT SQL/Lesson 11/Slide 31 of 72
  • 32. 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. ©NIIT SQL/Lesson 11/Slide 32 of 72
  • 33. 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 ©NIIT SQL/Lesson 11/Slide 33 of 72
  • 34. 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 ©NIIT SQL/Lesson 11/Slide 34 of 72
  • 35. 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 ©NIIT to commit SQL/Lesson 11/Slide 35 of 72
  • 36. 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 ©NIIT SQL/Lesson 11/Slide 36 of 72
  • 37. Implementing Transactions and Cursors Identify why User2 is unable to execute the transaction (Contd.) Inconsistent Analysis ® Aninconsistent analysis problem is also known as the non-repeatable problem Phantom Reads ®A phantom read is also known as the phantom problem ©NIIT SQL/Lesson 11/Slide 37 of 72
  • 38. 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 ©NIIT SQL/Lesson 11/Slide 38 of 72
  • 39. 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 ©NIIT SQL/Lesson 11/Slide 39 of 72
  • 40. Implementing Transactions and Cursors Identify why User2 is unable to execute the transaction (Contd.) Intent Locks ® Indicatesthat 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 ©NIIT SQL/Lesson 11/Slide 40 of 72
  • 41. 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 ©NIIT SQL/Lesson 11/Slide 41 of 72
  • 42. 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 ©NIIT SQL/Lesson 11/Slide 42 of 72
  • 43. 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 ©NIIT SQL/Lesson 11/Slide 43 of 72
  • 44. 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 ©NIIT SQL/Lesson 11/Slide 44 of 72
  • 45. 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 ©NIIT SQL/Lesson 11/Slide 45 of 72
  • 46. 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 ©NIIT SQL/Lesson 11/Slide 46 of 72
  • 47. 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 ©NIIT SQL/Lesson 11/Slide 47 of 72
  • 48. 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 ©NIIT SQL/Lesson 11/Slide 48 of 72
  • 49. 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 T R A N S A C T IO N A T R A N S A C T IO N B D IS T R IB U T O R PRO DUCTS ©NIIT SQL/Lesson 11/Slide 49 of 72
  • 50. 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 ©NIIT SQL/Lesson 11/Slide 50 of 72
  • 51. Implementing Transactions and Cursors Deadlock (Contd.) By default, SQL Server does not enforce timeout period Syntax SET LOCK_TIMEOUT [timeout_period] ©NIIT SQL/Lesson 11/Slide 51 of 72
  • 52. Implementing Transactions and Cursors Just a Minute... What is a deadlock? How can you customize deadlocks? ©NIIT SQL/Lesson 11/Slide 52 of 72
  • 53. 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 ©NIIT SQL/Lesson 11/Slide 53 of 72
  • 54. 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. ©NIIT SQL/Lesson 11/Slide 54 of 72
  • 55. 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 ……………………………………. ……………………………………. ©NIIT SQL/Lesson 11/Slide 55 of 72
  • 56. 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 ©NIIT SQL/Lesson 11/Slide 56 of 72
  • 57. 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]}] ©NIIT SQL/Lesson 11/Slide 57 of 72
  • 58. 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 ©NIIT SQL/Lesson 11/Slide 58 of 72
  • 59. 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 ] ] ©NIIT SQL/Lesson 11/Slide 59 of 72
  • 60. 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 ©NIIT SQL/Lesson 11/Slide 60 of 72
  • 61. 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 ©NIIT SQL/Lesson 11/Slide 61 of 72
  • 62. 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. ©NIIT SQL/Lesson 11/Slide 62 of 72
  • 63. 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 ©NIIT SQL/Lesson 11/Slide 63 of 72
  • 64. 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 ©NIIT SQL/Lesson 11/Slide 64 of 72
  • 65. Implementing Transactions and Cursors Identify the steps required to create the report (Contd.) -- Close the cursor CLOSE curDepartment -- Deallocate the cursor. DEALLOCATE curDepartment ©NIIT SQL/Lesson 11/Slide 65 of 72
  • 66. 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 ©NIIT SQL/Lesson 11/Slide 66 of 72
  • 67. 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 …………………………………….. …………………………………….. ©NIIT SQL/Lesson 11/Slide 67 of 72
  • 68. 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. ©NIIT SQL/Lesson 11/Slide 68 of 72
  • 69. 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 ©NIIT SQL/Lesson 11/Slide 69 of 72
  • 70. 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. ©NIIT SQL/Lesson 11/Slide 70 of 72
  • 71. 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. ©NIIT SQL/Lesson 11/Slide 71 of 72
  • 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) ©NIIT SQL/Lesson 11/Slide 72 of 72