Quantcast
Channel: SQL Server Blog
Viewing all articles
Browse latest Browse all 1849

SQL SERVER – FIX: Incorrect Syntax Near the Keyword ‘PROCEDURE’

$
0
0

Along with freelancing, consulting, I also spend time in replying to my blog comments to learn something new. Few such conversations end up in business deals, few in emails and few in the blog. This blog originates from one of such conversation regarding incorrect syntax.

Hi Pinal,
I am developing with ABCD, Inc. We are responsible to maintain software and released patches. The software uses SQL Server as back-end. I have created a script to update my application database for a new functionality. In this update i need to alter a stored procedure. I have an ALTER PROCEDURE script that works fine, but I need to check if the procedure exists and do some more stuff. Here are the errors.

Msg 156, Level 15, State 1, Line 6
Incorrect syntax near the keyword ‘PROCEDURE’.
Msg 137, Level 15, State 2, Line 11
Must declare the scalar variable “@input”.
Msg 156, Level 15, State 1, Line 19
Incorrect syntax near the keyword ‘PROCEDURE’.
Msg 134, Level 15, State 1, Line 24
The variable name ‘@output’ has already been declared. Variable names must be unique within a query batch or stored procedure.
Msg 137, Level 15, State 2, Line 24
Must declare the scalar variable “@input”.

What am I doing wrong here? The script is as follows (over simplified):

IF NOT EXISTS
(
    SELECT name FROM sys.procedures WHERE Name = 'MyProc' 
)
BEGIN
    CREATE PROCEDURE MyProc 
        @input int = 120
    AS
    BEGIN
        DECLARE @output DATETIME
        SELECT @output = DATEADD(MINUTE, -@input, GETDATE())
    END
END
ELSE
BEGIN
    ALTER PROCEDURE MyProc 
        @input int = 120
    AS
    BEGIN
        DECLARE @output DATETIME
        SELECT @output = DATEADD(MINUTE, -@input, GETDATE())
    END
END

I replied with the solution.

SQL SERVER - FIX: Incorrect Syntax Near the Keyword 'PROCEDURE' syntax-error-01-800x580

SOLUTION/WORKAROUND

I think you can’t alter the procedure inside the IF clause Try using it as a dynamic SQL. Here is the modified version. I have enclosed CREATE and ALTER under EXEC.

IF NOT EXISTS
(
    SELECT name FROM sys.procedures WHERE Name = 'MyProc' 
)
BEGIN
    EXEC('CREATE PROCEDURE MyProc 
        @input int = 120
    AS
    BEGIN
        DECLARE @timestamp DATETIME
        SELECT @timestamp = DATEADD(MINUTE, -@input, GETDATE())
    END')
END
ELSE
BEGIN
    EXEC('ALTER PROCEDURE MyProc 
        @input int = 120
    AS
    BEGIN
        DECLARE @timestamp DATETIME
        SELECT @timestamp = DATEADD(MINUTE, -@input, GETDATE())

    END')
END

I hope this would help someone to save time and energy.

Reference: Pinal Dave (http://blog.sqlauthority.com)

First appeared on SQL SERVER – FIX: Incorrect Syntax Near the Keyword ‘PROCEDURE’


Viewing all articles
Browse latest Browse all 1849

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>