SQL Server:Subselect IS NULL THEN'VALUE'

时间:2017-08-08 00:43:43

标签: sql-server

我试图在SQL Server中的值IS NULL时返回字符串结果。

我正在做的一个例子如下。这是一个子选择查询...

SELECT 
    stockitems.code AS StockCode, 
    stockitems.description AS 
ShortDescription,
    (SELECT 
         CASE remaining 
            WHEN NULL 
               THEN 'NO LEVEL' 
            ELSE remaining 
         END 
     FROM StockItemAlertLevels  
     WHERE StockItems.ID = StockItemAlertLevels.StockItemID) AS RemainingLevel
FROM
    stockitems
WHERE 
    StockItems.Attribute1 = '1'
ORDER BY 
    StockItems.Code

无论我做什么,如果结果为NULL,我都无法更改子选择的输出结果。并非SELECT语句的所有返回结果都会在子选择中返回结果 - 这是我需要将输出设置为“NO LEVEL”的位置。子选择永远不会返回多个结果。

希望这是有道理的。

1 个答案:

答案 0 :(得分:0)

我想你想要COALESCE()

SELECT si.code As StockCode, si.description AS ShortDescription,
       (SELECT COALESCE(remaining, 'NO LEVEL')     
        FROM StockItemAlertLevels sal
        WHERE si.ID = sal.StockItemID
       ) as RemainingLevel
FROM stockitems si
WHERE si.Attribute1 = '1'
ORDER BY si.Code;

我怀疑,你的问题不是remainingNULL,而是没有匹配。您可以将COALESCE()移到子查询之外,但我建议LEFT JOIN

SELECT si.code As StockCode, si.description AS ShortDescription,
       COALESCE(remaining, 'NO LEVEL') as RemainingLevel
FROM stockitems si LEFT JOIN
     StockItemAlertLevels sal
     ON si.ID = sal.StockItemID
WHERE si.Attribute1 = '1'
ORDER BY si.Code;