0

I have a really simple query like:

BEGIN TRY
BEGIN TRAN;
    DECLARE @CurrentPassword VARCHAR(255) = (SELECT TOP 1 [Password] 
                                             FROM Employee 
                                             WHERE @EmpGuid = EmpGuid)
    IF (@Password = @CurrentPassword)
        UPDATE [Employee] 
        SET [Password] = @NewPassword 
        WHERE @EmpGuid = EmpGuid

    SELECT 1;
    ELSE
        SELECT 2;

    COMMIT TRAN
END TRY
BEGIN CATCH
    ROLLBACK TRAN
END CATCH

But I really don't know why in my else clause I get

Incorrect syntax near 'ELSE'

What am I doing wrong? Regards

1

2 Answers 2

1

You you want to have more than one statement after the IF, you must use a BEGIN .... END block - like this:

BEGIN TRY
BEGIN TRAN;
    DECLARE @CurrentPassword VARCHAR(255) = (SELECT TOP 1 [Password] 
                                             FROM Employee 
                                             WHERE @EmpGuid = EmpGuid)
    IF (@Password = @CurrentPassword)
    BEGIN     --- you need a *BEGIN* here!!!
        UPDATE [Employee] 
        SET [Password] = @NewPassword 
        WHERE @EmpGuid = EmpGuid

        SELECT 1;
    END        --- and the *END* for your new *BEGIN*
    ELSE
        SELECT 2;

    COMMIT TRAN
END TRY
BEGIN CATCH
    ROLLBACK TRAN
END CATCH
Sign up to request clarification or add additional context in comments.

Comments

0

Use explicitly begin . . end

BEGIN TRY
BEGIN TRAN
    DECLARE @CurrentPassword VARCHAR(255) = (SELECT TOP 1 [Password] 
                                             FROM Employee 
                                             WHERE @EmpGuid = EmpGuid)
    IF (@Password = @CurrentPassword)
    BEGIN

        UPDATE [Employee] 
        SET [Password] = @NewPassword 
        WHERE @EmpGuid = EmpGuid

    SELECT 1
    END

    ELSE

    BEGIN
        SELECT 2
    END

    COMMIT TRAN
END TRY
BEGIN CATCH
    ROLLBACK TRAN
END CATCH

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.