title: When does RAISERROR fire in a stored procedure?
body: <p>I've got a stored procedure that contains a try-catch block.  In the catch block I call raiserror() to rethrow the error with some context.</p>
  
  <p>I was expecting that if an error occurred the raiserror() would be called and execution would immediately return from the stored procedure to the calling code.  However, this doesn't appear to be the case.  It looks like execution of the stored procedure continues until it hits a return statement, then the raiserror() takes effect.</p>
  
  <p>Is this correct - that raiserror() won't have an effect until return is called or the end of the stored procedure is reached?</p>
  
  <p>I'm using SQL Server 2012.</p>
  
  <p><strong>EDIT:</strong>
  in reply to request for details of the stored procedure, here's the relevant snippet of code:</p>
  
  <pre><code>DECLARE @ErrMsg VARCHAR(127) = 'Error in stored procedure ' + OBJECT_NAME(@@PROCID) + ': %s';
  
  declare @UpdateDateRecordCount table (LastUpdated datetime, NumberRecords int);
  begin try;
      insert into @UpdateDateRecordCount (LastUpdated, NumberRecords)
      exec sp_ExecuteSql 
          @UpdateCountQuery, 
          N'@LastUpdated datetime', 
          @LastUpdated = @LastUpdated;
  
      if @@rowcount &lt;= 0
      begin;
          return 0;
      end; 
  end try
  begin catch;
      declare @InsertError varchar(128) = 'Error getting updated date record count: ' 
          + ERROR_MESSAGE();
      RAISERROR (@ErrMsg, 16, 1, @InsertError);
  end catch;
  
  -- Attempt to loop through the records in @UpdateDateRecordCount...
  </code></pre>
  
  <p>The @UpdateCountQuery argument will be set to something like:</p>
  
  <pre><code>N'select LastUpdated, count(*) from dbo.Part where LastUpdated &gt; @LastUpdated group by LastUpdated;'
  </code></pre>