Search code examples
sql-serverfunctionsql-server-2008table-valued-parameters

To not return anything if SQL Server CASE value is NULL


I have a function which returns multiple rows of data with one column based on certain conditions.

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
)

When there are values for Fruits and Vegetables in the table, every thing is fine. But if the value for first two cases are not present then the output returned(from last 3 queries) is

NULL
NULL
NULL

Is there a way I can avoid those NULL and return nothing similar to the first two queries.


Solution

  • I in no way expect this to be the confirmed answer, I am just posting this to show you an answer to your comment above:

     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