Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

'IF' function?

Status
Not open for further replies.

mikeEd

Programmer
Nov 26, 2001
160
0
0
GB
Is there, in MSSQL, a function equivalent to MySQL's
IF(expr1, expr2, expr3) (if expr1 then return expr2, else return expr3)?
 
SQL Server has iif() in its OLAP Services but for some strange reason it's not supported in T-SQL.
 

Use the Case statement in T-SQL.

Case When expr1 then expr2 else expr3 end

Example Select statement.

Select
Col1, Col2,
Col3=Case When Col1>=Col2 Then 1 Else -1 End
From TblName Terry L. Broadbent
FAQ183-874 contains tips for posting questions in these forums.
NOTE: Reference to the FAQ is not directed at any individual.
 
Hi,

Can we use CASE statements to do something else than select fields ? Like, having two "WHERE" clauses that we can selected using a CASE ?

Like...

Select
TblName.Col1, TblName.Col2,TblName.Col3,TblName2.Col1
From TblName,TblName2

CASE TblName.Col1 =1

THEN WHERE .....

ELSE WHERE .....

END

Can we do that ? I've been trying to do that for quite a long time...and I have yet to find a way to do it :(

Thanks

Dominic

 

Dominic,

No you can't use the CASE statment in that manner. You should write the query in the following manner.

Select
a.Col1, a.Col2,ca.Col3,
b.Col1 As Col1b
From TblName Inner Join TblName2
On a.keycol=b.keycol2

Where (a.Col1=1 And <other criteria>)
Or (a.col1<>1 And <another criteria>)

Terry L. Broadbent
FAQ183-874 contains tips for posting questions in these forums.
NOTE: Reference to the FAQ is not directed at any individual.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top