Select value if condition in SQL Server [duplicate

2019-06-14 22:18发布

问题:

This question already has an answer here:

  • How do I perform an IF…THEN in an SQL SELECT? 25 answers
  • SQL returning custom values based on query results 2 answers

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?

回答1:

Try Case

SELECT   stock.name,
      CASE 
         WHEN stock.quantity <20 THEN 'Buy urgent'
         ELSE 'There is enough'
      END
FROM stock


回答2:

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