What happened to my IF / ELSE? "ELSE: Incorrect syntax next to" ELSE "."

I have some code similar to this:

DECLARE @IdentificationNumber INT
DECLARE @Foreign_ID BIGINT

IF ((SELECT COUNT(*) FROM [main-table] WHERE [identification-number] = @IdentificationNumber) > 0)

    SET @Foreign_ID = (SELECT [Foreign_ID] FROM [main-table] WHERE [identification-number] = @IdentificationNumber) 

    BEGIN
        UPDATE [main-table]
        SET [column1] = '', [column2] = '', [column3] = ''
        WHERE [Foreign_ID] = @Foreign_ID
    END

    BEGIN
        UPDATE [table2]
        SET [column4] = '', [column5] = '', [column6] = ''
        WHERE [Foreign_ID] = @Foreign_ID
    END

    BEGIN
        UPDATE [table3] 
        SET [column7] = '', [column8] = '', [column9] = ''
        WHERE [Foreign_ID] = @Foreign_ID
    END
    -- and so on, up to 14

ELSE -- "Incorrect syntax near 'ELSE'.

    BEGIN
        INSERT into ... -- blah blah blah. 
    END

      

... but I get an error when I try to use ELSE

:Incorrect syntax near 'ELSE'.

+3


source to share


1 answer


IF - Else

syntax

If condition
begin
--statement
end
else 
begin
--statement
end

      



In your request, after the first one, IF statement

you will group the operators Begin - End

, they should all be wrapped inside Begin - End

. how

IF ((SELECT COUNT(*) FROM [main-table] WHERE [identification-number] = @IdentificationNumber) > 0)
Begin -- Missing
    SET @Foreign_ID = (SELECT [Foreign_ID] FROM [main-table] WHERE [identification-number] = @IdentificationNumber) 

    BEGIN
        UPDATE [main-table]
        SET [column1] = '', [column2] = '', [column3] = ''
        WHERE [Foreign_ID] = @Foreign_ID
    END

    BEGIN
        UPDATE [table2]
        SET [column4] = '', [column5] = '', [column6] = ''
        WHERE [Foreign_ID] = @Foreign_ID
    END

    BEGIN
        UPDATE [table3] 
        SET [column7] = '', [column8] = '', [column9] = ''
        WHERE [Foreign_ID] = @Foreign_ID
    END
END -- Missing
else
....

      

+12


source







All Articles