0

I have a query to first check if something exists. If yes, insert something into a table variable. Otherwise, insert something else into the same table variable.

IF NOT EXISTS (SELECT 1 FROM @Main WHERE CustomerId = @CustomerId)
(   
    BEGIN  
        INSERT INTO @Result 
            SELECT .... 
            FROM ... 
            WHERE...
   END
)
ELSE
   INSERT INTO @Result  
       SELECT .... 
       FROM ...  
       WHERE...

For some reason I keep getting the errors below complaining inside the NOT EXISTS condition... The ELSE part is completely fine.

Incorrect syntax near the keyword 'BEGIN'
Incorrect syntax near ')'
Incorrect syntax near '@Result'

Where did I do wrong?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
ichachan
  • 637
  • 1
  • 10
  • 34

2 Answers2

4

The parentheses don't belong around the BEGIN/END:

IF NOT EXISTS (SELECT 1 FROM @Main WHERE CustomerId = @CustomerId)   
BEGIN  
    INSERT INTO @Result 
        SELECT .... FROM ... WHERE...
END
ELSE . . .

I would also suggest that you list the columns for @Result for the INSERT. This can prevent future problems.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
2

try this

IF NOT EXISTS (SELECT 1 FROM @Main WHERE CustomerId = @CustomerId)

     BEGIN  
          INSERT INTO @Result 
          SELECT .... FROM ... WHERE...
     END

ELSE

     BEGIN
          INSERT INTO @Result 
          SELECT .... FROM ... WHERE...
     END
asmgx
  • 7,328
  • 15
  • 82
  • 143