title: How do I conditionally create a stored procedure in SQL Server?
body: <p>As part of my integration strategy, I have a few SQL scripts that run in order to update the database. The first thing all of these scripts do is check to see if they need to run, e.g.:</p>
  
  <pre><code>if @version &lt;&gt; @expects
      begin
          declare @error varchar(100);
          set @error = 'Invalid version. Your version is ' + convert(varchar, @version) + '. This script expects version ' + convert(varchar, @expects) + '.';
          raiserror(@error, 10, 1);
      end
  else
      begin
          ...sql statements here...
      end
  </code></pre>
  
  <p>Works great! Except if I need to add a stored procedure. The "create proc" command must be the only command in a batch of sql commands. Putting a "create proc" in my IF statement causes this error:</p>
  
  <pre>
  'CREATE/ALTER PROCEDURE' must be the first statement in a query batch.
  </pre>
  
  <p>Ouch! How do I put the CREATE PROC command in my script, and have it only execute if it needs to?</p>