34

In a query selection I would like to display the result whether a field satisfies a condition.

Imagine that I have a table called stock. This table has a column that tells me the number of each item in the stock.

What I would like to do is something like this:

SELECT 
    stock.name, IF (stock.quantity <20, "Buy urgent", "There is enough")
FROM stock

Is there any function in SQL Server to do that?

coumarc9
  • 7
  • 2
Rumpelstinsk
  • 3,107
  • 3
  • 30
  • 57

2 Answers2

65

Try Case

SELECT   stock.name,
      CASE 
         WHEN stock.quantity <20 THEN 'Buy urgent'
         ELSE 'There is enough'
      END
FROM stock
Ram
  • 3,092
  • 10
  • 40
  • 56
  • I'll use this but seems such a shame to have to do this when all I want is a boolean value. can't see why mssql can't let me do "select (stock.quantity <20) As booleanValue" – Joshua Duxbury Oct 05 '16 at 11:07
  • 1
    @JoshuaDuxbury If you want a boolean value you can try something like http://stackoverflow.com/a/7778500/2246380 – Ram Oct 05 '16 at 15:30
6

Have a look at CASE statements
http://msdn.microsoft.com/en-us/library/ms181765.aspx

Daniel Hollinrake
  • 1,768
  • 2
  • 19
  • 39