Why does the CREATE PROCEDURE statement fail when I use it with IF Statement here?

16,908

Adding GO after your IF statement shows that this is the end of your first query batch.

Read more here:

http://msdn.microsoft.com/en-us/library/ms188037.aspx

IF OBJECT_ID('[dbo].[myStoredProc]') IS not NULL
    DROP PROCEDURE dbo.myStoredProc
GO

This will prevent your error from occurring.

Share:
16,908
vel
Author by

vel

Updated on June 08, 2022

Comments

  • vel
    vel about 2 years

    I am trying to DROP a stored procedure if it exists and then CREATE it by doing this way:

    IF OBJECT_ID('[dbo].[myStoredProc]') IS not NULL
        DROP PROCEDURE dbo.myStoredProc
    
    
    CREATE PROCEDURE [dbo].[myStoredProc]
    (
        @parameter1 BIT
    ) AS
    
    IF @parameter1 = 1
        BEGIN
                 ....
    

    But it complains that :

    "CREATE PROCEDURE must be the only statement in the batch"

    Question: How can I fix my script to overcome this?