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

时间:2018-03-01 21:09:50

标签: sql-server function sql-server-2008 table-valued-parameters

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

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并且返回与前两个查询类似的内容。

3 个答案:

答案 0 :(得分:2)

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

 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

答案 1 :(得分:2)

...
SELECT 'Fruit Exists'
WHERE EXISTS(Select 1 FROM Fruits WHERE FruitID = @FruitId)
...

答案 2 :(得分:1)