title: Nested stored procedures containing TRY CATCH ROLLBACK pattern?
body: <p>I'm interested in the side effects and potential problems of the following pattern:</p>
  
  <pre><code>CREATE PROCEDURE [Name]
  AS
  BEGIN
      BEGIN TRANSACTION
      BEGIN TRY
          [...Perform work, call nested procedures...]
      END TRY
      BEGIN CATCH
          ROLLBACK TRANSACTION
          RAISERROR [rethrow caught error using @ErrorNumber, @ErrorMessage, etc]
      END CATCH
  END
  </code></pre>
  
  <p>To the best of my understanding this pattern is sound when used with a single procedure - the procedure will either complete all of its statements without error, or it will rollback all actions and report the error.</p>
  
  <p>However when one stored procedure calls another stored procedure to do some sub-unit of work (with the understanding that the smaller procedure is sometimes called on its own) I see an issue coming about with relation to rollbacks - an informational message (Level 16) is issued stating <code>The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION.</code>. This I assume is because the rollback in the sub-procedure is always rolling back the outer-most transaction, not just the transaction started in the sub-procedure.</p>
  
  <p>I do want the whole thing rolled back and aborted if any error occurs (and the error reported to the client as an SQL error), I'm just not sure of all the side effects that come from the outer layers trying to rollback a transaction that has already been rolled back. Perhaps a check of <code>@@TRANCOUNT</code> before doing a rollback at each TRY CATCH layer?</p>
  
  <p>Finally there is the client end (Linq2SQL), which has it's own transaction layer:</p>
  
  <pre><code>try
  {
      var context = new MyDataContext();
      using (var transaction = new TransactionScope())
      {       
              // Some Linq stuff
          context.SubmitChanges();
          context.MyStoredProcedure();
          transactionComplete();
      }
  }
  catch
  {
      // An error occured!
  }
  </code></pre>
  
  <p>In the event that a stored procedure, "MySubProcedure", called <em>inside</em> MyStoredProcedure raises an error, can I be sure that everything previously done in MyStoredProcedure will be rolled back, all the Linq operations made by SubmitChanges will be rolled back, and finally that the error will be logged? Or what do I need to change in my pattern to ensure the whole operation is atomic, while still allowing the child parts to be used individually (i.e. the sub-procedures should still have the same atomic protection)</p>