Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ternary operator in SQL Server 2008?

Tags:

sql

sql-server

SQL query:

SELECT * 
FROM Account 
WHERE (type <>100000002 ? Id='something': Id=null)

but it shows error :

Incorrect syntax near '?'

Please help me.

like image 688
Suman Banerjee Avatar asked Feb 03 '14 11:02

Suman Banerjee


People also ask

Can we use ternary operator in SQL Server?

In this article, we will see how to use ternary Operator which is unfortunately not supported in SQL so then we are going to see an alternative of a conditional operator to work with SQL.

How do you write a 3 condition ternary operator?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.

How do you use a ternary operator example?

It helps to think of the ternary operator as a shorthand way or writing an if-else statement. Here's a simple decision-making example using if and else: int a = 10, b = 20, c; if (a < b) { c = a; } else { c = b; } printf("%d", c); This example takes more than 10 lines, but that isn't necessary.

What is the use and syntax of ternary operator give one example?

We use the ternary operator in C to run one code when the condition is true and another code when the condition is false. For example, (age >= 18) ? printf("Can Vote") : printf("Cannot Vote");


1 Answers

This is for SQL Server. IIF is not available in SQL Server 2008 or earlier.

 SELECT * 
    FROM Account 
    WHERE 
    Id=IIF(type<> 100000002,"something",null )

If you are using SQL Server 2008 or earlier, then try this.

  SELECT * 
    FROM Account 
    WHERE (Id= CASE WHEN type <>100000002 THEN 'something'  ELSE null END)
like image 128
Suman Banerjee Avatar answered Sep 19 '22 08:09

Suman Banerjee