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.:
if @version <> @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
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:
'CREATE/ALTER PROCEDURE' must be the first statement in a query batch.
Ouch! How do I put the CREATE PROC command in my script, and have it only execute if it needs to?
Here’s what I came up with:
Wrap it in an EXEC(), like so:
Works like a charm!