简体   繁体   中英

How do I create an If-Then-Else in T-SQL

I have some negative values coming back from a query. I would like them to just be zero. How do I write a condition in my sql query that returns zero if the value is below a certain value.

sol:

CASE WHEN  CONVERT(float,dt.FQI53X02_101)  <  1.3  THEN 0 ELSE CONVERT(float,dt.FQI53X02_101) END AS  FQI53X02_101

You dont use If-Then-Else in the actual query (you can use them but thats something else)...

What you use is a Case statement... Try this

Select
    Case When [Value] < 0 Then 0 Else [Value] End
From 
    Example

If you want it as part of your query, wrap the return inside a CASE statement. Example from MSDN is below

SELECT     'Price Category' = 

        CASE 

            WHEN price IS NULL THEN 'Not yet priced'

            WHEN price < 10 THEN 'Very Reasonable Title'

            WHEN price >= 10 and price < 20 THEN 'Coffee Table Title'

            ELSE 'Expensive book!'

        END,

    CAST(title AS varchar(20)) AS 'Shortened Title'

FROM titles

ORDER BY price
( ABS(Value) + Value ) / 2

编辑 - 现在问题已经改变,这不起作用

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM