如果sql server中的值为null,则为0

时间:2014-11-04 05:38:28

标签: sql sql-server

在下面的查询中,我选择带有currentstock的产品。现在,如果当前库存为空,我想要替换0。请帮助我这样做。

SELECT   p.ProductID,
       p.ProductName,
       (SELECT ISNULL( CurrentStock,0.00) 
        FROM   Productstatus PS
        WHERE  PS.ProductID =p.ProductID
               AND PS.LocationID = 1
               AND PS.StatusDateTime= '2014-08-27'
               and PS.productid=p.productid) CurrentStock
FROM   Product P
LEFT OUTER JOIN LocationProductMap LMP ON LMP.ProductID=P.ProductID
WHERE LMP.ProductInFlow=1

3 个答案:

答案 0 :(得分:2)

SELECT   p.ProductID,
   p.ProductName,
   ISNULL((SELECT ISNULL( CurrentStock,0.00) 
    FROM   Productstatus PS
    WHERE  PS.ProductID =p.ProductID
           AND PS.LocationID = 1
           AND PS.StatusDateTime= '2014-08-27'
           and PS.productid=p.productid),0) CurrentStock
FROM   Product P
LEFT OUTER JOIN LocationProductMap LMP ON LMP.ProductID=P.ProductID
WHERE LMP.ProductInFlow=1

答案 1 :(得分:0)

你可以使用

Select case when (CurrentStock) is null then 0 else (CurrentStock) end from table

答案 2 :(得分:0)

单个COALESCE将在您的查询中完成工作。它也比ISNULL功能更有效。

SELECT   p.ProductID,
   p.ProductName,
   COALESCE((SELECT CurrentStock 
    FROM   Productstatus PS
    WHERE  PS.ProductID =p.ProductID
           AND PS.LocationID = 1
           AND PS.StatusDateTime= '2014-08-27'
           and PS.productid=p.productid),0) CurrentStock
FROM   Product P
LEFT OUTER JOIN LocationProductMap LMP ON LMP.ProductID=P.ProductID
WHERE LMP.ProductInFlow=1
相关问题