t-sql 2012 if else error

  • What is wrong with following sql? Incorrect syntax near the keyword 'ELSE'.
      BEGIN
      IF
      (Select value from O.dbo.Cust where  attributeID = 997)  ='N'
      select c1.personID
          ,c1.enrollmentID
          ,c1.value
          ,c1.date
          ,c1.customGUID
          ,c1.districtID
       ,c1.attributeID
       ,c2.personID
          ,c2.enrollmentID
          ,c2.value
          ,c2.date
          ,c2.customGUID
          ,c2.districtID
       ,c2.attributeID
       From  O.dbo.Cust c1     
       JOIN (select personID
          ,enrollmentID
          ,value
          ,date
          ,customGUID
          ,districtID
       ,attributeID from O.dbo.Cust
        where  attributeID = 997 and value='N' )  AS c2  
       on c2.personID=c1.personID
          and c1.date=c2.date
       where  c1.attributeID = 1452
      END
      ELSE
      BEGIN
       (select c1.personID
          ,c1.enrollmentID
          ,c1.value
          ,c1.date
          ,c1.customGUID
          ,c1.districtID
       --,attributeID = 3370   From  O.dbo.Cust c1     
       JOIN (select personID
          ,enrollmentID
          ,value
          ,date
          ,customGUID
          ,districtID
       ,attributeID = 3371
       from O.dbo.Cust
        where  attributeID = 997 and value <>'N' )  AS c2  
       on c2.personID=c1.personID
          and c1.date=c2.date
       where  c1.attributeID = 1452
       )
       END
       GO

  • It's IF <expr> BEGIN, not BEGIN IF <expr>

    Thom~

    Excuse my typos and sometimes awful grammar. My fingers work faster than my brain does.
    Larnu.uk

  • I would also like to add that the BEGIN...END isn't even necessary in this case.  It's used to group t-sql statement together.  However in your case it will either do one or the other.

    Simple Examples:

    --This works
    DECLARE @var INT = 1

    BEGIN
     IF @var = 0
     SELECT GETDATE()
     ELSE
     SELECT GETDATE() + 1
    END

    GO

    --So does this
    DECLARE @var INT = 1

    IF @var = 0
    BEGIN
     SELECT GETDATE()
    END
    ELSE
    BEGIN
     SELECT GETDATE() + 1
    END

    GO

    --but you can simply do this
    DECLARE @var INT = 1

    IF @var = 0
    SELECT GETDATE()
    ELSE
    SELECT GETDATE() + 1


    SELECT quote FROM brain WHERE original = 1
    0 rows returned

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply