Home sql-server What does it look like if the design of if ... then...

What does it look like if the design of if … then in SQL Select?

Author

Date

Category

How can I perform if … then in the SQL SELECT statement?

For example:

select if (obsolete = 'n' or Instock = 'Y'? 1: 0) as saleable, * from Product

Question translation How to Perform An if … Then in An SQL SELECT? @eric labashosky


Answer 1, Authority 100%

The Case statement is the nearest if analogue in SQL and is supported in all versions of SQL Server.

Select Cast (
  Case
     WHEN OBSOLETE = 'N' OR Instock = 'Y'
      THEN 1.
     ELSE 0.
  END AS BIT) as saleable, *
From Product.

The only case when you need to use Cast – if you need a result in the form of a boolean value; If you are satisfied with the type int , the solution is as follows:

select case
  WHEN OBSOLETE = 'N' OR Instock = 'Y'
   THEN 1.
   ELSE 0.
  END AS SALEABLE, *
From Product.

Operator Case You can implement in another Operator Case and even include in the aggregated object.

SQL Server Denali (SQL Server 2012) adds an operator iif also present in Access : (It is noted Martin Smith )

select iIF (obsolete = 'n' or instock = 'y', 1, 0) as selable, * from Product

Answer translation How to Perform An If … Then in An SQL SELECT? @Darrel Miller .

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions