title: T SQL Nested IF...ELSE in BEGIN...END
body: <p>I would like some guidance on why there are issues with this procedure. I seem to get an error that states "Incorrect syntax near the keyword 'END'."</p>
  
  <p>I've added comments where I think the issues are. labeled (x) and (y) in the in-code-comments. I used DataGrip for syntax highlighting and that's how I know these pairings exist. But I still don't understand why.</p>
  
  <p>I am aware that a <code>CASE</code> statement could solve this issue. But I would like to know why it is not working with <code>IF...ELSE</code></p>
  
  <pre><code>CREATE PROCEDURE AuthenticateUser(
    @UserName NVARCHAR(50),
    @Password NVARCHAR(50),
    @Result INT OUTPUT
  ) AS
    BEGIN -- Cannot find a corresponding END
      SET NOCOUNT ON
  
      DECLARE @userID INT
  
      IF exists(SELECT UserID FROM Users WHERE UserName = @UserName)
        BEGIN -- paired with END (y)
          SET @userID = (SELECT UserID FROM Users WHERE UserName = @UserName AND Password = dbo.EncryptPassword(@Password, Salt))
  
          IF @userID IS NULL -- Paired with END (x)
            SET @Result = 0
          ELSE
            SET @Result = 1
  
        END -- paired with IF (x)
      ELSE
        SET @Result = 0
  
    END -- paired with BEGIN (y)
  GO
  </code></pre>