2009-12-28 15 views
22

Come si scrive un'istruzione IF con più argomenti in T-SQL?Istruzione argomento IF multiplo - T-SQL

attuale errore Origine:

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 

Si getta il seguente errore:

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

+1

Funziona sulla mia macchina? Sto pensando che l'errore potrebbe essere tra il tuo 'BEGIN' e' END'. Oppure, se non hai nulla tra 'BEGIN' e' END', questo sarebbe il problema. – Aaronaught

+0

Grazie per l'input. Era la sezione '--do some work' che stava causando il problema. Sto costruendo una dichiarazione SQL dinamica ... ugh! –

risposta

38

Si sta facendo bene. Il blocco di codice vuoto è ciò che sta causando il tuo problema. Non è la struttura delle condizioni :)

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 
1

Questo è il modo per creare complesse espressioni booleane: li si combinano con AND e OR. Lo snippet che hai postato non genera alcun errore per l'IF.

1

Sembra funzionare correttamente.

Se si dispone di un vuoto BEGIN ... END blocco si potrebbe vedere

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

1

Non so quale sia il problema, questo sembra funzionare bene?

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 
1

Il codice è valido (con una eccezione). È richiesto il codice tra BEGIN e END.

Sostituire

--do some work 

con

print '' 

penso che magari "END e non "AND"