35

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?

0

2 Answers 2

65

Try Case

SELECT   stock.name,
      CASE 
         WHEN stock.quantity <20 THEN 'Buy urgent'
         ELSE 'There is enough'
      END
FROM stock
2
  • 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" Commented Oct 5, 2016 at 11:07
  • 1
    @JoshuaDuxbury If you want a boolean value you can try something like stackoverflow.com/a/7778500/2246380
    – Ram
    Commented Oct 5, 2016 at 15:30
6

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

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.