我有一个函数,它根据特定条件返回多行数据和一列。
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并且返回与前两个查询类似的内容。
答案 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)
使用COALESCE替换NULL值。
https://msdn.microsoft.com/en-us/library/ms190349(v=sql.110).aspx