title: Statements after END in stored procedure
body: <p>I came across an interesting problem today.  I was altering a stored procedure and put a select statement at the very end.  It was meant to be temporary and just for working with the data.  I was surprised to find out later that the statement got saved and was executing whenever the SP ran.</p>
  
  <pre><code>SET ANSI_NULLS ON
  GO
  
  -- Comments usually go here and are saved as part of the SP
  ALTER PROCEDURE [dbo].[MySP]
      @param INT
  AS
  BEGIN
      --Your normal SQL statements here
  END
  
  --You can also add SQL statements here
  select * from LargeTable
  
  --You have access to the params
  select @param
  </code></pre>
  
  <p>It makes sense that everything is saved, not just what is inside BEGIN/END, otherwise the comments and <code>SET ANSI_NULLS</code>, etc. would disappear.  I'm a little confused with what starts where, so I have a few questions:</p>
  
  <ol>
  <li><code>SET ANSI_NULLS</code> gets saved as part of the SP.  I have confirmed that each SP has its own value.  How does SQL Server know to save this as part of the SP since it's not referenced before?  Does it do a full scan of the current environment state, then when <code>ALTER PROCEDURE</code> runs it saves the state (possibly only non-default values)?</li>
  <li>Apparently the BEGIN/END are optional and have no intrinsic meaning. Why are they even included then?  They give a false sense of scope that doesn't exist.  It seems to me no BEGIN/END and a GO at the end would make the most sense.</li>
  </ol>