Intro to tsql unit 12

639 views
577 views

Published on

Published in: Technology, Business
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
639
On SlideShare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
36
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Intro to tsql unit 12

  1. 1. Introduction To SQL Unit 12 Modern Business Technology Introduction To TSQL Unit 12 Developed by Michael Hotek
  2. 2. Transaction Management <ul><li>Most of the following discussion of transaction management is specific to Sybase SQL Server and MS SQL Server </li></ul><ul><li>But, the principles can be applied to virtually any DBMS </li></ul>
  3. 3. Transactions <ul><li>Transactions by definition are a logical unit of work </li></ul><ul><li>A logical unit of work is a SQL operation or a set of SQL statements executed against a database </li></ul><ul><ul><li>Usually include at least one DML statement </li></ul></ul><ul><ul><li>Changes the database from one consistent state to another </li></ul></ul><ul><li>A transaction can have two outcomes </li></ul><ul><ul><li>When it completes successfully, it is &quot;committed&quot; or &quot;saved&quot; </li></ul></ul><ul><ul><li>When a transaction fails, it is &quot;rolled back&quot; or &quot;undone&quot; </li></ul></ul>
  4. 4. <ul><li>Another definition is a single recoverable unit of work that executes either: </li></ul><ul><ul><li>Completely </li></ul></ul><ul><ul><li>Not at all </li></ul></ul><ul><li>A transaction can be anything from a single DML command to a series of commands (multiple inserts or deletes) </li></ul>Transactions
  5. 5. Outcomes <ul><li>After a transaction is committed, it can not be undone </li></ul><ul><li>When a transaction is rolled back, all modifications of the transaction are undone </li></ul><ul><li>Partial execution of a transaction is not allowed </li></ul><ul><li>delete authors can only have two possible outcomes: </li></ul><ul><ul><li>All rows are deleted (committed) or </li></ul></ul><ul><ul><li>None of the rows are deleted (rolled back) </li></ul></ul>
  6. 6. Need for Transactions <ul><li>Transactions are the result of business rules being applied to the database world </li></ul><ul><li>These rules state that an operation either completes successfully or none of the operations can be applied </li></ul><ul><li>In the following scenario, we will consider a bank teller machine </li></ul>
  7. 7. Need for Transactions <ul><li>The business function we are trying to apply is the transfer of funds from a savings to a checking account </li></ul><ul><li>The amount debited from the savings account must be added to the checking account </li></ul><ul><li>Both the debit and the credit must occur or neither must occur </li></ul>
  8. 8. Need for Transactions <ul><li>Here are the possible problems in transferring $1000 </li></ul><ul><ul><li>Partial transfer </li></ul></ul><ul><ul><ul><li>Money is debited, but not credited </li></ul></ul></ul><ul><ul><li>Another operation against your account could conflict with the transfer </li></ul></ul><ul><ul><li>Another operation could see invalid data </li></ul></ul><ul><ul><ul><li>The debit does not work, but the money is credited. A check for an amount greater than should be in the checking account is processed and approved </li></ul></ul></ul><ul><ul><li>Another operation could see data at the wrong time </li></ul></ul>
  9. 9. <ul><li>Transaction management is implemented to cover the following issues: </li></ul><ul><ul><li>Protect data from software, hardware, or power failure </li></ul></ul><ul><ul><li>Provide access to multiple user </li></ul></ul><ul><ul><li>Prevent simultaneous read and write of the same data by multiple users </li></ul></ul><ul><li>Transaction control is implemented via three methods </li></ul><ul><ul><li>Locking </li></ul></ul><ul><ul><li>Transaction control statements </li></ul></ul><ul><ul><li>Error management </li></ul></ul>Implementing
  10. 10. Data Storage <ul><li>How data is physically stored by SQL Server is beyond the scope of this class </li></ul><ul><li>However, there is one principle that must be understood in order to continue with the next topic </li></ul><ul><li>A table's data is stored in a series of pages called data pages </li></ul><ul><li>SQL Server handles this page allocation internally and also &quot;knows&quot; where to find the particular data via a set of internal structures </li></ul>
  11. 11. Locking <ul><li>Locking is automagically handled by SQL Server via a process called the Lock Manager </li></ul><ul><li>As reads or writes are performed on a data page, the lock manager places a lock on that page </li></ul><ul><li>This ensures that simultaneous transactions do not interfere with each other </li></ul><ul><li>Without this locking, you may get data inconsistency in a multi-user environment </li></ul><ul><li>The locking mechanism also reduces availability of data </li></ul>
  12. 12. Locking <ul><li>All locking decisions are handled by SQL Server </li></ul><ul><li>There are two levels of locking </li></ul><ul><ul><li>page and table </li></ul></ul><ul><li>Page locks are less restrictive than table locks, because the lock is placed only on a single page and therefore on a small subset of data </li></ul><ul><li>Page locks are used whenever possible </li></ul>
  13. 13. Table Locks <ul><li>A table lock is the most restrictive lock </li></ul><ul><li>As it's name implies, it is a lock that covers the entire table </li></ul><ul><li>A table lock is implemented via a means called escalation </li></ul><ul><li>If a user is going to access an entire table: </li></ul><ul><ul><li>an update with no where clause </li></ul></ul><ul><li>SQL Server will escalate the page lock to a table lock </li></ul><ul><li>Once a SQL statement accumulates 200 page locks, it is escalated to a table lock </li></ul>
  14. 14. Locking <ul><li>Obviously there can only be one table lock </li></ul><ul><li>So, it would seem that you want to avoid this if at all possible </li></ul><ul><li>The type of lock acquired is generally not a concern as SQL Server tries to maintain the most appropriate lock for the least duration of time </li></ul>
  15. 15. Granularity <ul><li>The granularity of a lock refers to the amount of data that can be locked at one time. This can range from a single page to an entire database </li></ul><ul><li>By increasing the lock granularity, the processing required to obtain a lock decreases. But this also degrades performance </li></ul><ul><li>As lock granularity decreases, the amount of processing required to maintain and coordinate the locks increases </li></ul>
  16. 16. Types of Page Locks <ul><li>There are three types of locks </li></ul><ul><ul><li>Shared </li></ul></ul><ul><ul><ul><li>Multiple transactions can lock a shared page </li></ul></ul></ul><ul><ul><ul><li>No transactions can change the page </li></ul></ul></ul><ul><ul><ul><li>Usually released as soon as the page is read </li></ul></ul></ul><ul><ul><li>Exclusive </li></ul></ul><ul><ul><ul><li>Only one transaction can lock a page </li></ul></ul></ul><ul><ul><ul><li>Other transactions must wait until the lock is released </li></ul></ul></ul><ul><ul><ul><li>Exists for the duration of the transaction </li></ul></ul></ul><ul><ul><li>Update </li></ul></ul><ul><ul><ul><li>Allows reads, but will not allow shared or exclusive locks </li></ul></ul></ul><ul><ul><ul><li>Becomes an exclusive lock when the page is ready to be modified </li></ul></ul></ul><ul><ul><ul><li>Is an internal lock to help avoid deadlocks </li></ul></ul></ul><ul><ul><ul><li>Exists for the duration of the transaction </li></ul></ul></ul>
  17. 17. Lock Interactions <ul><li>Can another process: </li></ul><ul><li>Command Lock Select Modify </li></ul><ul><li>select title_id from titles shared yes no </li></ul><ul><li>delete titles exclusive no no </li></ul><ul><li>where price > 25 </li></ul><ul><li>insert into titles values (…) exclusive no no </li></ul><ul><li>update titles set type= update, yes no </li></ul><ul><li>'general' where type = then exclusive no </li></ul><ul><li>'business' </li></ul><ul><li>Locking is affected by: </li></ul><ul><ul><li>Indexes </li></ul></ul><ul><ul><li>Transactions </li></ul></ul><ul><ul><li>Isolation Levels </li></ul></ul><ul><ul><li>Table and page level locking </li></ul></ul>
  18. 18. Isolation Levels <ul><li>The ANSI standard defines four level of isolation for transactions </li></ul><ul><ul><li>Level 0 allows dirty reads (You can see data that has been changed, but not necessarily committed, by another user </li></ul></ul><ul><ul><li>Level 1 prevents dirty reads </li></ul></ul><ul><ul><li>Level 2 prevents non-repeatable reads </li></ul></ul><ul><ul><li>Level 3 prevents phantom reads </li></ul></ul><ul><li>The higher the isolation level, the higher the consistency </li></ul><ul><li>The higher the isolation level, the lower the concurrency </li></ul>
  19. 19. Isolation Levels <ul><li>All higher levels include all of the restrictions of the lower levels </li></ul><ul><li>Level 0 </li></ul><ul><ul><li>No shared locks for reads or exclusive locks on pages or tables being changed. An update still acquires a shared lock for its read </li></ul></ul><ul><li>Level 1 </li></ul><ul><ul><li>Exclusive lock on objects being changed. Hold lock until end of transaction </li></ul></ul><ul><ul><li>Shared locks on pages being searched. Release locks after object is processed. </li></ul></ul>
  20. 20. Isolation Levels <ul><li>Level 2 </li></ul><ul><ul><li>Exclusive lock on pages being changed. Hold lock until end of transaction </li></ul></ul><ul><ul><li>Shared lock on pages being searched. Remove lock after processing object </li></ul></ul><ul><li>Level 3 </li></ul><ul><ul><li>Exclusive lock on pages being changed </li></ul></ul><ul><ul><li>Shared lock on pages/tables being searched </li></ul></ul><ul><ul><li>Hold all locks until end of transaction (accumulate locks) </li></ul></ul><ul><li>The default isolation level for SQL Server is 1 </li></ul><ul><li>The default isolation level for the ANSI-92 standard is 3 </li></ul><ul><li>The current isolation level can be gotten from @@isolation </li></ul>
  21. 21. Holdlock <ul><li>noldlock/noholdlock is an option for a select statement that overrides the isolation level set for the duration of the select statement </li></ul><ul><li>Holdlock </li></ul><ul><ul><li>Enforces isolation level 3 </li></ul></ul><ul><ul><li>Makes a shared lock more restrictive, by causing the server to hold all shared locks until the transaction is complete </li></ul></ul><ul><ul><li>Applies a shared pages lock if the search argument references indexed columns, otherwise it applies a table lock </li></ul></ul><ul><ul><li>Use only if strictly necessary </li></ul></ul>
  22. 22. Noholdlock <ul><li>Use the noholdlock option only if you want SQL Server to release any shared locks regardless of isolation level </li></ul>
  23. 23. Holdlock <ul><li>begin tran </li></ul><ul><ul><li>declare @avg_adv money </li></ul></ul><ul><ul><li>select @avg_adv = avg(advance) from titles holdlock where type = 'business' </li></ul></ul><ul><ul><li>if @avg_adv > 5000 </li></ul></ul><ul><ul><li>select title from titles where type = 'business' and advance > @avg>adv </li></ul></ul><ul><li>commit tran </li></ul><ul><li>Since the average must remain constant for the duration of the transaction, holdlock will prevent anyone from writing to the titles table until the transaction is complete </li></ul>
  24. 24. Deadlock <ul><li>A deadlock can occur when two processes hold locks on a page on which the other process holds a conflicting lock </li></ul><ul><li>SQL Server detects this and aborts one of the transactions </li></ul>
  25. 25. Deadlock <ul><li>SQL Server will detect a deadlock and chooses the user with the least amount of CPU time as the &quot;victim&quot; </li></ul><ul><li>Even the &quot;winner&quot; will see a significant decrease in performance </li></ul>
  26. 26. Deadlock <ul><li>Application need to program for the possibility of a deadlock (error 1205 in Sybase SQL Server) </li></ul><ul><li>If a deadlock occurs, the application should resubmit the transaction </li></ul>
  27. 27. Avoiding Deadlocks <ul><li>To minimize the possibility of a deadlock </li></ul><ul><ul><li>Have all transaction access the tables in the same order </li></ul></ul><ul><ul><li>Use holdlock only when repeatable reads are necessary </li></ul></ul><ul><ul><li>Avoid long running transactions; make transactions small and commit as soon as possible </li></ul></ul><ul><ul><li>Avoid user input while you have a holdlock on a table </li></ul></ul><ul><ul><li>Avoid numerous simultaneous executions of DML commands like insert, update, delete </li></ul></ul>
  28. 28. Avoiding Deadlocks <ul><li>The best way to avoid deadlocks is to write transaction in the same order. Avoid the following: </li></ul><ul><ul><li>begin tran begin tran </li></ul></ul><ul><ul><li>update table A update table B </li></ul></ul><ul><ul><li>update table B update table A </li></ul></ul><ul><ul><li>commit tran commit tran </li></ul></ul><ul><li>Wherever possible try to use stored procedures to perform transactions to ensure consistent access order to tables </li></ul>
  29. 29. Transaction Control <ul><li>Provides the control required for managing transaction </li></ul><ul><li>Enables the grouping of SQL commands in a transaction that meet business requirements </li></ul><ul><li>Enables a programmer to influence SQL Server's locking strategy </li></ul><ul><li>Creates predictable effects when committing or rolling back transactions </li></ul><ul><li>begin transaction and commit transaction mark the beginning and end of a transaction </li></ul>
  30. 30. Transaction Control <ul><li>There are three transaction control statements </li></ul><ul><ul><li>begin tran </li></ul></ul><ul><ul><ul><li>Alerts SQL Server that a transaction is beginning. You can optionally name a transaction. </li></ul></ul></ul><ul><ul><li>rollback tran </li></ul></ul><ul><ul><ul><li>Undoes the changes either to the named savepoint or the beginning of the transaction. Execution continues with the next statement </li></ul></ul></ul><ul><ul><li>commit tran </li></ul></ul><ul><ul><ul><li>End the transaction and saves changes to the database </li></ul></ul></ul>
  31. 31. Rollback <ul><li>Before a commit is issued, a transaction can be either partially rolled back to a savepoint or completely rolled back </li></ul><ul><li>After a commit is issued, a transaction can not be rolled back </li></ul>
  32. 32. Savepoints <ul><li>In unchained mode, you can set up savepoints in a transaction </li></ul><ul><li>These serve as an intermediate point in a transaction </li></ul><ul><li>There could be cases where you want to only rollback a portion of the work you have done. </li></ul><ul><li>save {transaction | tran } savepoint_name </li></ul>
  33. 33. Savepoints <ul><li>To undo all statements or procedures between a savepoint and the rollback use: </li></ul><ul><li>rollback {transaction | tran | work} savepoint_name </li></ul><ul><li>Always name savepoints </li></ul><ul><li>After a rollback, execution continues with the statement immediately following the rollback </li></ul>
  34. 34. Savepoint Example <ul><li>A bank can charge a fee for every use of an ATM. The specific transaction might fail, but the charge still needs to be applied </li></ul><ul><li>begin tran </li></ul><ul><li>update service_charge set service_charge = service_charge + .50 where account_num = '99999' </li></ul><ul><li>save tran service_charge </li></ul><ul><li>update savings set balance = balance - 500 where account_num = '99999' </li></ul><ul><li>if @@transtate = 2 </li></ul><ul><li>begin </li></ul><ul><li>select @@error </li></ul><ul><li>rollback tran service_charge </li></ul><ul><li>return </li></ul><ul><li>end </li></ul><ul><li>... </li></ul>
  35. 35. Error Processing <ul><li>You can monitor a transaction through two global variables: </li></ul><ul><ul><li>@@error detects errors during/after statements execute </li></ul></ul><ul><ul><li>@@transtate monitors the current state of the transaction </li></ul></ul><ul><li>Value Meaning </li></ul><ul><li>0 transaction in progress </li></ul><ul><li>1 transaction committed </li></ul><ul><li>2 previous statement aborted and transaction still in progress </li></ul><ul><li>3 transaction aborted/statement rolled back </li></ul><ul><li>@@transtate is reset after insert, update, delete </li></ul>
  36. 36. Error Handling <ul><li>Failure with a rollback (@@transtate = 3) </li></ul><ul><ul><li>Errors of severity level 19 or higher are fatal and will immediately abort the transaction and roll back all statements to the beginning of the transaction </li></ul></ul><ul><li>Failure with continue (@@transtate = 2) </li></ul><ul><ul><li>Errors from a failed statement cause the statement to fail, but other statements are committed </li></ul></ul><ul><li>No error, completed (@@transtate = 1) </li></ul><ul><ul><li>Transaction finished and saved all its changes </li></ul></ul><ul><li>No error, in progress (@@transtate = 0) </li></ul>
  37. 37. Error Handling <ul><li>@@transtate is not always set to 2 or 3 when a statement fails </li></ul><ul><li>Insert into a null into a column that does not allow nulls </li></ul><ul><ul><li>An error is reported for each attempt </li></ul></ul><ul><ul><li>All rows that contain valid data will be inserted </li></ul></ul><ul><ul><li>The error is found in @@error </li></ul></ul><ul><ul><li>There is no indication in @@transtate </li></ul></ul><ul><li>@@error should be used exclusively to: </li></ul><ul><ul><li>Maintain atomicity of transactions </li></ul></ul><ul><ul><ul><li>If any commands fail, undo all changes </li></ul></ul></ul><ul><ul><ul><li>Abort the transaction using a return </li></ul></ul></ul><ul><ul><ul><li>Ensure each batch contains only one transaction so you can predict what is rolled back on an abort </li></ul></ul></ul>
  38. 38. Error Handling <ul><li>If you are using insert statements in a transaction, you should always check @@error </li></ul><ul><li>begin tran </li></ul><ul><li>insert … </li></ul><ul><ul><li>if @@error != 0 </li></ul></ul><ul><ul><li>begin </li></ul></ul><ul><ul><li>rollback tran </li></ul></ul><ul><ul><li>return </li></ul></ul><ul><ul><li>end </li></ul></ul><ul><ul><li>… </li></ul></ul><ul><li>commit tran </li></ul>
  39. 39. @@rowcount <ul><li>@@rowcount will tell you how many rows were affected by a statement </li></ul><ul><ul><li>An insert, update, or delete may affect more than one row </li></ul></ul><ul><ul><li>A select into a variable may not return any rows which could cause invalid results later in the transaction </li></ul></ul><ul><li>If you expect rows and @@rowcount = 0 </li></ul><ul><ul><li>Issue a rollback tran </li></ul></ul><ul><ul><li>Issue a return to abort the transaction </li></ul></ul>
  40. 40. Reporting Errors <ul><li>If an error occurs, we want to return a user friendly message of what happened. </li></ul><ul><li>This is accomplished by using raiserror </li></ul><ul><li>Develop a numbering system for error messages </li></ul><ul><ul><li>20001 - 21000 = update errors </li></ul></ul><ul><ul><li>21001 - 22000 = insert errors... </li></ul></ul><ul><li>Standardize you error output </li></ul><ul><li>Add a new error message with sp_addmessage </li></ul>
  41. 41. Report Errors Example <ul><li>exec sp_addmessage 40000, &quot;An error occurred while updating '%1!' table with a publisher ID of '%2!'.&quot; </li></ul><ul><li>declare @error int, </li></ul><ul><ul><li>@rows int </li></ul></ul><ul><li>begin tran </li></ul><ul><li>update publishers set pub_id = 'a' where pub_id = '0736' </li></ul><ul><li>select @error = @@error, @rows = @@rowcount </li></ul><ul><li>if @error != 0 </li></ul><ul><li>begin </li></ul><ul><li>rollback tran </li></ul><ul><li>raiserror 40000,'publishers','0736' </li></ul><ul><li>return </li></ul><ul><li>end... </li></ul><ul><li>commit tran </li></ul><ul><li>Results </li></ul><ul><li>Msg 40000, Level 16, State 1: </li></ul><ul><li>Line11 </li></ul><ul><li>An error occurred while updating publishers table with publisher ID of 0736. </li></ul>
  42. 42. Unit 12 Review <ul><li>A transaction is a logical unit of work </li></ul><ul><li>Transactions can be committed or rolled back </li></ul><ul><li>Once a transaction is committed it can not be rolled back </li></ul><ul><li>Pages are locked as they are accessed. A large number of page locks will escalate into a table lock </li></ul><ul><li>There are four isolation levels which can be used to control the locking in the database </li></ul><ul><li>Use the holdlock/noholdlock to override an isolation level setting </li></ul><ul><li>Deadlocks occur when two transaction are trying to obtain a lock on a page where the other has a conflicting lock </li></ul><ul><li>Deadlocks need to be avoided at all costs </li></ul><ul><li>There are three transaction control statements: begin tran, commit tran, rollback tran </li></ul><ul><li>There are two transaction modes: chained and unchained </li></ul><ul><li>Savepoints can be implemented to preserve some of the work done in the event of an error </li></ul><ul><li>@@error detects errors during or after statement execution </li></ul>
  43. 43. Unit 12 Review <ul><li>@@transtate is used to check the state of a transaction - It has four values </li></ul><ul><li>@@rowcount stores the number of rows affected by a given statement </li></ul><ul><li>Raiserror is used to return an error message back to an application </li></ul>
  44. 44. Unit 12 Exercises <ul><li>Time allotted for exercises is 1/2 hour </li></ul>

×