SQL查询,如果value为null则返回1

时间:2013-02-19 16:51:52

标签: tsql null ssms

我有一个查询返回我们系统中设置的汇率值。并非每个订单都有汇率(currate.currentrate),因此它返回空值。

我可以让它返回1而不是null吗?

类似if语句的东西可能是:

 if isnull(currate.currentrate) then 1 else currate.currentrate 

以下是我的查询。我非常感谢你的帮助!

 SELECT     orderhed.ordernum, orderhed.orderdate, currrate.currencycode,  currrate.currentrate
 FROM         orderhed LEFT OUTER JOIN
                  currrate ON orderhed.company = currrate.company AND orderhed.orderdate = currrate.effectivedate

6 个答案:

答案 0 :(得分:100)

您可以使用CASE声明。

SELECT 
    CASE WHEN currate.currentrate IS NULL THEN 1 ELSE currate.currentrate END
FROM ...

答案 1 :(得分:46)

您可以使用COALESCE

SELECT  orderhed.ordernum, 
    orderhed.orderdate, 
    currrate.currencycode,  
    coalesce(currrate.currentrate, 1) as currentrate
FROM orderhed 
LEFT OUTER JOIN currrate 
    ON orderhed.company = currrate.company 
    AND orderhed.orderdate = currrate.effectivedate

甚至IsNull()

SELECT  orderhed.ordernum, 
    orderhed.orderdate, 
    currrate.currencycode,  
    IsNull(currrate.currentrate, 1) as currentrate
FROM orderhed 
LEFT OUTER JOIN currrate 
    ON orderhed.company = currrate.company 
    AND orderhed.orderdate = currrate.effectivedate

以下文章有助于在COALESCEIsNull之间做出决定:

http://www.mssqltips.com/sqlservertip/2689/deciding-between-coalesce-and-isnull-in-sql-server/

答案 2 :(得分:10)

SELECT 
    ISNULL(currate.currentrate, 1)  
FROM ...

比获胜的答案更简洁,并做同样的事情

https://msdn.microsoft.com/en-us/library/ms184325.aspx

答案 3 :(得分:2)

SELECT orderhed.ordernum, orderhed.orderdate, currrate.currencycode,  

case(currrate.currentrate) when null then 1 else currrate.currentrate end

FROM orderhed LEFT OUTER JOIN currrate ON orderhed.company = currrate.company AND orderhed.orderdate = currrate.effectivedate  

答案 4 :(得分:0)

尝试如下...

CASE 
WHEN currate.currentrate is null THEN 1
ELSE currate.currentrate
END as currentrate

答案 5 :(得分:-1)

a)如果你想要值为null时为0

SELECT isnull(PartNum,0) AS PartNumber, PartID
FROM Part

b)如果在值为null时需要0,否则为1

SELECT 
  (CASE
    WHEN PartNum IS NULL THEN 0
    ELSE 1
  END) AS PartNumber,
  PartID
FROM Part