I have tried this:
if object_id('a_proc22') is not null
CREATE PROCEDURE a_proc22 AS SELECT 1
go
but it gives me a syntax error.
But this seemed to compile:
if object_id('a_proc22') is not null
EXEC('CREATE PROCEDURE a_proc22 AS SELECT 1')
go
Why is the first one incorrect?
I’m guessing the error is something like “CREATE/ALTER PROCEDURE must be the first statement in a query”, so, well, that means that
CREATE PROCEDUREmust be the first statement in a query. If you wrapped it up on anEXEC, then when its executed, it is the first statement on that query, so that’s why it works.