31

How do I write an IF statement with multiple arguments in T-SQL?

Current source error:

DECLARE @StartDate AS DATETIME
DECLARE @EndDate AS DATETIME

SET @StartDate = NULL
SET @EndDate = NULL

IF (@StartDate IS NOT NULL AND @EndDate IS NOT NULL) 
    BEGIN
        -- do some work
    END

It throws the following error:

Incorrect syntax near the keyword 'AND'. Incorrect syntax near the keyword 'AND'. Incorrect syntax near ')'.

3
  • 1
    Works on my machine? I'm thinking the error might be between your BEGIN and END. Or, if you have nothing between the BEGIN and END, that would be the problem. Commented Dec 28, 2009 at 20:06
  • Thanks for the input. It was the --do some work section that was causing the issue. I am building a dynamic SQL statement...ugh! Commented Dec 28, 2009 at 20:12
  • I get Incorrect syntax near 'END'. because of the empty block. Put x: before the comment (or a real statement). Commented Nov 23, 2018 at 8:16

5 Answers 5

49

You are doing it right. The empty code block is what is causing your issue. It's not the condition structure :)

DECLARE @StartDate AS DATETIME

DECLARE @EndDate AS DATETIME

SET @StartDate = NULL
SET @EndDate = NULL

IF (@StartDate IS NOT NULL AND @EndDate IS NOT NULL) 
    BEGIN
        print 'yoyoyo'
    END

IF (@StartDate IS NULL AND @EndDate IS NULL AND 1=1 AND 2=2) 
    BEGIN
        print 'Oh hey there'
    END
Sign up to request clarification or add additional context in comments.

Comments

2

Your code is valid (with one exception). It is required to have code between BEGIN and END.

Replace

--do some work

with

print ''

I think maybe you saw "END and not "AND"

Comments

1

That's the way to create complex boolean expressions: combine them with AND and OR. The snippet you posted doesn't throw any error for the IF.

Comments

1

Seems to work fine.

If you have an empty BEGIN ... END block you might see

Msg 102, Level 15, State 1, Line 10 Incorrect syntax near 'END'.

Comments

1

Not sure what the problem is, this seems to work just fine?

DECLARE @StartDate AS DATETIME
DECLARE @EndDate AS DATETIME

SET @StartDate = NULL
SET @EndDate = NULL

IF (@StartDate IS NOT NULL AND @EndDate IS NOT NULL) 
    BEGIN
        Select 'This works just fine' as Msg
    END
Else
    BEGIN
    Select 'No Lol' as Msg
    END

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.