Two If's And An Else I am trying to run this t-sql query but I keep getting an error of


  Incorrect syntax near the keyword 'END'


How should this be re-written in order to execute properly?  What I want to achieve is if my variable @d2 &gt;= GetDate() I want to run a check to see if @d2 exists in my table farquard if it does then back-up @d1 by 1 day, if it does not then back-up @d1 by two days.

This is my with errors syntax, can someone help me?

Declare @d1 datetime, @d2 datetime
Set @d1 = '01/01/2013'
Set @d2 = '01/04/2013'

if @d2 &gt;= CAST(GetDate() As Date)
Begin
  if Not Exists(Select TOP 1 * FROM farquard WHERE CAST(stinktoothruth As Date) = @d2)
      BEGIN
        Set @d2 = CAST(GetDate()-2 As Date)
    END
ELSE
      BEGIN
        Set @d2 = CAST(GETDATE()-1 As Date
      END
  END
End
The very last CAST is missing a parenthesis

Set @d2 = CAST(GetDate()-2 As Date


should be 

Set @d2 = CAST(GetDate()-2 As Date)


That fixes the main issue. (also, once that was fixed you had and extra END at the very end which I removed--or alternately, adding an additional BEGIN.)

    Declare @d1 datetime, @d2 datetime
    Set @d1 = '01/01/2013'
    Set @d2 = '01/04/2013'

    if @d2 &gt;= CAST(GetDate() As Date)
      Begin
        if Not Exists(Select TOP 1 * FROM farquard WHERE CAST(stinktoothruth As Date) = @d2)
          BEGIN
            Set @d2 = CAST(GetDate()-2 As Date)
          END
      END
    ELSE
          BEGIN
            Set @d2 = CAST(GETDATE()-1 As Date)
          END
--END REMOVED


OR, alternately,

Declare @d1 datetime, @d2 datetime
Set @d1 = '01/01/2013'
Set @d2 = '01/04/2013'

if @d2 &gt;= CAST(GetDate() As Date)
Begin
  if Not Exists(Select TOP 1 * FROM farquard WHERE CAST(stinktoothruth As Date) = @d2)
      BEGIN
        Set @d2 = CAST(GetDate()-2 As Date)
    END
ELSE
--BEGIN ADDED
begin
      BEGIN
        Set @d2 = CAST(GETDATE()-1 As Date)
      END
  END
end