Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple argument IF statement - T-SQL

Tags:

tsql

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

like image 462
Michael Kniskern Avatar asked Dec 28 '09 20:12

Michael Kniskern


People also ask

How do you write multiple if conditions in SQL?

END TRY BEGIN CATCH SELECT ERROR_MESSAGE() AS 'Message' RETURN -1 END CATCH END --The above works I then insert this below and these if statement become nested---- IF(@A!= @SA) BEGIN exec Store procedure @FIELD = 15, ... more params... END IF(@S!= @SS) BEGIN exec Store procedure @FIELD = 10, ... more params...

How do you combine if statements in SQL?

Yes, PL/SQL allows us to nest if statements within if-then statements. i.e, we can place an if then statement inside another if then statement. if (condition1) then -- Executes when condition1 is true if (condition2) then -- Executes when condition2 is true end if; end if; SQL.

Can we use if condition in SQL query?

Example 6: IF with BEGIN and END block We can use BEGIN and END statement block in a SQL IF statement. Once a condition is satisfied, it executes the code inside the corresponding BEGIN and End block. We can specify multiple statements as well with SQL IF statement and BEGIN END blocks.

How do I write if else in SQL Server?

The syntax for the IF...ELSE statement in SQL Server (Transact-SQL) is: IF condition {... statements to execute when condition is TRUE...} [ ELSE {...


1 Answers

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 
like image 91
Shaun Avatar answered Oct 11 '22 16:10

Shaun