tags:

views:

91

answers:

5

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 ')'.

+1  A: 

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.

Remus Rusanu
+1  A: 

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'.

astander
+1  A: 

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
RandomNoob
A: 

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"

Gabriel McAdams
+2  A: 

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
Shaun F