title: TSQL Alter procedure if it exists - syntax error
body: <p>I'm trying to understand what specifically is happening in SQL that means the following syntax is not allowed (and I'm finding it hard to search for):</p>
  
  <pre><code>IF (OBJECT_ID('..sp_cake', 'P') is not null)
    ALTER PROC sp_cake
    as 
    select 1
  </code></pre>
  
  <p>I would expect the ALTER to be valid because T-SQL is wrapping it up in its own BEGIN-END block and nothing bad could happen with the rest of the script block.</p>
  
  <p>This is what T-SQL is doing, wrapping everything up and keeping it cleanly separated:</p>
  
  <pre><code>IF (OBJECT_ID('..sp_cake', 'P') is not null)
  BEGIN
      ALTER PROC [dbo].[sp_cake]
      as 
      BEGIN
          select 1
      END
  END
  </code></pre>
  
  <p>And these examples would be the simplest expression of what I think I'm doing (and these are syntactically correct)</p>
  
  <pre><code>IF (OBJECT_ID('..sp_cake', 'P') is not null)
   select 1
  
  
  IF (OBJECT_ID('..sp_cake', 'P') is null)
   select 1 -- i.e. this works and 1 is the output
  </code></pre>
  
  <p>I have read that the CREATE or ALTER must be the first statement in a query block, but I don't understand why.</p>
  
  <hr>
  
  <p>I know that I can get around this problem by either:</p>
  
  <ul>
  <li>creating a dummy sproc and then altering it outside of an IF block, or;</li>
  <li>creating a string of the entire sproc and executing it as a statement;</li>
  </ul>
  
  <p>but I don't see why it is not valid to test for existence and then ALTER.</p>