0

I'm struggling to understand why the below SQL will not work. I've put a comment (----------Fine up to Here), which is where SQL Server will accept the code when I parse/save the Store proceedure.

The bit below that, it will not take. Still new to SQL so any help would be great.

The error I receive is, Incorrect syntax near the keyword 'ELSE'. The "ELSE" being the one under the comment I mentioned above.

What I also don't understand is, If I change the IF and the BEGIN round, SQL accepts it (below)? I thought ELSE IF was not possible.

----------Fine up to Here
ELSE 
IF (@GrabTypeID = '')
    BEGIN


****************************************
Code below

**************************************
IF  (@GrabtypeID NOT IN (SELECT GRABTYPEID FROM Mytable) AND @GrabtypeID != '')     OR

(@Variable1 NOT IN (SELECT ID FROM Mytable) AND @Variable1 !='')                                                                            


BEGIN 
    SELECT @ErrorMessage ='The GrabTypeID or the ID is an invalid value'        
    RAISERROR (@ErrorMessage, 16, 1)

PRINT 'Invalid Parameters passed Through'

    RETURN
END 

ELSE 
    BEGIN 

IF (@GrabtypeID ! ='')


TRUNCATE TABLE Datatable1
TRUNCATE TABLE Datatable2

INSERT Datatable1
SELECT * FROM Referencetable1

INSERT Datatable2
SELECT * FROM REFERENCETABLE2

END

----------Fine up to Here

ELSE 
    BEGIN

IF (@GrabTypeID = '')


TRUNCATE TABLE Datatable1
TRUNCATE TABLE Datatable2

INSERT Datatable1 
SELECT * FROM REFERENCETABLE1 WHERE CATEGORY = 4

INSERT Datatable2 
SELECT * FROM REFERENCETABLE2 WHERE CATEGORY = 4

END 

GO
1
  • 1
    You are missing a BEGIN marker after the IF keyword. Commented Oct 17, 2017 at 18:30

1 Answer 1

2

Your format is a little weird. You could make it work the way you have it, but I think it would be better to use this format:

IF expression
BEGIN
SELECT
END
ELSE IF expression
BEGIN
SELECT
END
ELSE IF expression
BEGIN
SELECT
END

Specifically, change this:

ELSE 
BEGIN 

IF (@GrabtypeID ! ='')

To this (in both places):

ELSE IF (@GrabtypeID ! ='')
BEGIN
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.