SQL查询,如果值为null,则返回1
我有一个查询,返回在我们的系统中设置的汇率值。 不是每个订单都有一个汇率(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
您可以使用CASE
语句。
SELECT CASE WHEN currate.currentrate IS NULL THEN 1 ELSE currate.currentrate END FROM ...
你可以使用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
这里有一篇文章帮助决定COALESCE
和IsNull
:
http://www.mssqltips.com/sqlservertip/2689/deciding-between-coalesce-and-isnull-in-sql-server/
SELECT ISNULL(currate.currentrate, 1) FROM ...
是比获胜的答案less冗长,并做同样的事情
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
尝试像下面…
CASE WHEN currate.currentrate is null THEN 1 ELSE currate.currentrate END as currentrate
a)如果当值为null时你想要0
SELECT isnull(PartNum,0) AS PartNumber, PartID FROM Part
b)如果你希望0值为空,否则为1
SELECT (CASE WHEN PartNum IS NULL THEN 0 ELSE 1 END) AS PartNumber, PartID FROM Part