如果SQL Server CASE值为NULL,则不返回任何内容

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如果SQL Server CASE值为NULL,则不返回任何内容相关的知识,希望对你有一定的参考价值。

我有一个函数,它根据某些条件返回多行数据和一列。

ALTER FUNCTION [dbo].[GetFavoriteFruits]
(   
    @FruitId uniqueidentifier
)
RETURNS TABLE 
AS
RETURN 
(
    Select Name FROM Fruits WHERE FruitID = @FruitId
    UNION ALL
    Select Name FROM Vegetables WHERE VegetableID = @FruitId
    UNION ALL
    Select
    CASE
    WHEN EXISTS(Select Name FROM Fruits WHERE FruitID = @FruitId) THEN 'Fruit Exists'
    END
    UNION ALL
    Select
    CASE
    WHEN EXISTS(Select Name FROM Vegetables WHERE VegetableID = @FruitId) THEN 'Vegetable Exists'
    END
    UNION ALL
    Select
    CASE
    WHEN EXISTS(Select Name FROM Fruits WHERE FruitID = @FruitId) OR EXISTS(Select Name FROM Vegetables WHERE VegetableID = @FruitId) THEN 'Either Fruit or Vegetable exists'
    END
)

当表中有水果和蔬菜的价值时,每件事都很好。但是如果前两个案例的值不存在,则返回的输出(来自最后3个查询)是

NULL
NULL
NULL

有没有办法可以避免那些NULL,并返回与前两个查询类似的内容。

答案

我绝不希望这是确认的答案,我只是张贴这个来向您显示上述评论的答案:

 ALTER FUNCTION [dbo].[GetFavoriteFruits]
(   
    @FruitId uniqueidentifier
)
RETURNS TABLE 
AS
RETURN 
(
    SELECT x.Name FROM (
    Select Name FROM Fruits WHERE FruitID = @FruitId
    UNION ALL
    Select Name FROM Vegetables WHERE VegetableID = @FruitId
    UNION ALL
    Select
    CASE
    WHEN EXISTS(Select Name FROM Fruits WHERE FruitID = @FruitId) THEN 'Fruit Exists'
    END
    UNION ALL
    Select
    CASE
    WHEN EXISTS(Select Name FROM Vegetables WHERE VegetableID = @FruitId) THEN 'Vegetable Exists'
    END
    UNION ALL
    Select
    CASE
    WHEN EXISTS(Select Name FROM Fruits WHERE FruitID = @FruitId) OR EXISTS(Select Name FROM Vegetables WHERE VegetableID = @FruitId) THEN 'Either Fruit or Vegetable exists'
    END
) ) AS x
WHERE x.Name IS NOT NULL
另一答案
...
SELECT 'Fruit Exists'
WHERE EXISTS(Select 1 FROM Fruits WHERE FruitID = @FruitId)
...
另一答案

使用COALESCE替换NULL值。

https://msdn.microsoft.com/en-us/library/ms190349(v=sql.110).aspx

以上是关于如果SQL Server CASE值为NULL,则不返回任何内容的主要内容,如果未能解决你的问题,请参考以下文章

SQL Server - CASE 中的 CASE 检查 NULL

NULL记录SQL Server的奇怪主键问题

Mysql when case 批量更新

vb+sql 求和值为null时怎么处理?

SQL CASE语句

在 SQL Server 中检查多个值为 NULL 的列