code_junkie

IsolationLevel.RepeatableRead to prevent duplicates

Nov 11th, 2011
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. // table "package"
  2. // columns packageID, policyID, other data...
  3. //
  4. // table "insurancepolicy"
  5. // columns policyID, coverageAmount, other data...
  6.  
  7. using (SqlConnection conn = new SqlConnection(...))
  8. {
  9. sqlTransaction sqlTrans = conn.BeginTransaction(IsolationLevel.RepeatableRead);
  10.  
  11. // Calls a stored procedure that checks if the foreign key in the transaction table has a value.
  12. if (PackageDB.HasInsurancePolicy(packageID, conn))
  13. {
  14. sqlTrans.Commit();
  15. return false;
  16. }
  17.  
  18. // Insert row in foreign table.
  19. int policyID = InsurancePolicyDB.Insert(coverageAmount, conn);
  20. if (policyID <= 0)
  21. {
  22. sqlTrans.Rollback();
  23. return false;
  24. }
  25.  
  26. // Assign foreign key to parent table. If this fails, roll back everything.
  27. bool assigned = PackageDB.AssignPolicyID(packageID, policyID, conn);
  28. if (!assigned)
  29. {
  30. sqlTrans.Rollback();
  31. return false;
  32. }
  33. }
  34.  
  35. begin tran (read committed)
  36.  
  37. /* tentatively insert new Policy */
  38. insert Policy
  39.  
  40. /* attach Package to Policy if it's still free */
  41. update Package
  42. set Package.policy_id = @policy_id
  43. where Package.package_id = @package_id and Package.policy_id is null
  44.  
  45. if @@rowcount > 0
  46. commit
  47. else
  48. rollback
Add Comment
Please, Sign In to add comment