SQL Server:如何将空值视为零

时间:2009-10-21 21:14:18

标签: sql-server

以下是我正在尝试做的一个例子:

Select
S1.Name as S1Name,
S1.Itemcontent as S1ItemContent,
...
S2.Name as S2Name,
S2.Name as S2ItemContent,
**(S1.OrderValue * 1000*1000 + S2.OrderValue*1000 +  S3.OrderValue) as OrderValue**
From (joining s1, s2 and s3 on a particular value)
Order by OrderValue

当S1.OrderValue,S2.OrderValue或S3.OrderValue为null时,OrderValue也会变为null。我希望SQL Server在这种情况下将空值视为0。我怎么能这样做?

6 个答案:

答案 0 :(得分:11)

使用isNull函数,例如

isnull(s1.ordervalue,0)

如果值为null,则使用您提供的替代值作为第二个值。

答案 1 :(得分:4)

COALESCE (Value, 0)ISNULL (Value, 0)

答案 2 :(得分:3)

Coalesce返回第一个非null值。

**(coalesce(S1.OrderValue,0) * 1000 + coalesce(S2.OrderValue,0)*1000 +  coalesce(S3.OrderValue,0)) as OrderValue

答案 3 :(得分:3)

使用T-SQL Coalesce强制执行非空答案。例如:

COALESCE(S1.OrderValue, 0)

...将采用OrderValue值,除非它为NULL,在这种情况下采用0。

答案 4 :(得分:3)

您可以使用案例陈述。

SELECT title, price,
        Budget = CASE price
         WHEN price > 20.00 THEN 'Expensive'
          WHEN price BETWEEN 10.00 AND 19.99 THEN 'Moderate'
          WHEN price < 10.00 THEN 'Inexpensive'
          ELSE 'Unknown'
        END,
FROM titles

返回以下内容:

Title                  Price       Budget
---------------------- ----------- ---------------
Cooking with Computers 11.95       Moderate
Straight Talk About Co 19.99       Moderate
The Busy Executive's D 19.99       Moderate
You Can Combat Compute 2.99        Inexpensive
Silicon Valley Gastron 19.99       Moderate
The Gourmet Microwave  2.99        Inexpensive
But Is It User Friendl 22.95       Expensive
Secrets of Silicon Val 20.00       Moderate
Net Etiquette          (null)      Unknown   

从这里取得的例子(http://www.craigsmullins.com/ssu_0899.htm

答案 5 :(得分:2)

使用ISNULL(S1.ORDERVALUE,0)