Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2008 - Case / If statements in SELECT Clause [duplicate]

I have a Query that's supposed to run like this -


If(var = xyz) 
   SELECT col1, col2
ELSE IF(var = zyx)
   SELECT col2, col3
ELSE
   SELECT col7,col8

FROM 

.
.
.

How do I achieve this in T-SQL without writing separate queries for each clause? Currently I'm running it as


IF (var = xyz) {
  Query1
}
ELSE IF (var = zyx) {
  Query2
}
ELSE {
  Query3
}

That's just a lot of redundant code just to select different columns depending on a value. Any alternatives?

like image 580
Tejaswi Yerukalapudi Avatar asked Jul 13 '09 22:07

Tejaswi Yerukalapudi


People also ask

Can we use if statement in select query in SQL?

This isn't what the requester wanted, but is very useful to know that you can use if statements outside a select statement. EXISTS is good because it kicks out of the search loop if item is found. A COUNT runs until the end of table rows. Nothing to do with question, but something to know.

Can we use case in WHERE clause in SQL Server?

The case statement in SQL returns a value on a specified condition. We can use a Case statement in select queries along with Where, Order By, and Group By clause. It can be used in the Insert statement as well.


1 Answers

You are looking for the CASE statement

http://msdn.microsoft.com/en-us/library/ms181765.aspx

Example copied from MSDN:

USE AdventureWorks;
GO
SELECT   ProductNumber, Category =
      CASE ProductLine
         WHEN 'R' THEN 'Road'
         WHEN 'M' THEN 'Mountain'
         WHEN 'T' THEN 'Touring'
         WHEN 'S' THEN 'Other sale items'
         ELSE 'Not for sale'
      END,
   Name
FROM Production.Product
ORDER BY ProductNumber;
GO
like image 119
Sam Saffron Avatar answered Oct 15 '22 01:10

Sam Saffron