Search code examples
sql-servert-sqlnestedblock

SQL nesting BEGIN END Blocks gives SQL Error (102)


I'm getting the following error for this simple piece of SQL code. Any ideas why? Any BEGIN ... END block causes this error to occur

/* SQL Error (156): Incorrect syntax near the keyword 'END'. */

DECLARE @PROCESSEDCOUNT INT = 0
WHILE (@PROCESSEDCOUNT < 10)
BEGIN
    SET @PROCESSEDCOUNT +=1
    IF 1=1
    BEGIN
        -- Stuff happens here
    END
END 

This is running on SQL Server - MSSQL15


Solution

  • You must put something in between the BEGIN and END block For example:

    DECLARE @PROCESSEDCOUNT INT= 1
    
    WHILE (@PROCESSEDCOUNT < 10)
    BEGIN
        SET @PROCESSEDCOUNT +=1
        IF 1=1
        BEGIN
            PRINT '1'
        END
    END