如何检查 table 值参数是否为空或不在 where 子句内?

How to check if a table valued parameter is empty or not inside of a where clause?

我正在编写一个传递 table 值参数的函数。 在某些情况下,table 值参数可以为空。

所以,我的函数如下所示-

CREATE FUNCTION [dbo].[testTableValueParam]
(   
    @created_date datetime = null
    ,@Ids dbo.IdList readonly
)
RETURNS TABLE 
AS
RETURN 
(
     SELECT top 10
            name
            ,scores
            ,mgr_name

        from dbo.employee
        where
            created_date = @created_date
            and 
            employeeId in (select empid from @Ids)           --ignore this condition when @Ids is empty. 
)

我的 table 类型创建如下 -

CREATE TYPE [dbo].[IdList] AS TABLE(
    [empid] [nvarchar](11) NULL
)

我正在从 C# 代码调用我的函数。
在某些情况下 table 值参数将为空,在这些情况下,当 table 值参数为空时,我想忽略 where 子句中的条件。

我在搜索我的答案时浏览了一些链接,但之前 post 中建议的答案并没有解决我的问题。

所以,现在,当@Ids 参数为空时,它没有给我任何记录。
在某些 post 中,他们建议根本不要为 table 值传递参数,它会自动将其视为空 table.
但是我有一些情况需要用数据传递参数。
一些建议的答案,使用if exist(select 1 from @Ids)
但是,我不能在我的 where 子句中使用 if exist。

请提出任何建议。
非常感谢您的回复。

谢谢。

您可以使用 NOT EXISTS 运算符,例如...

CREATE FUNCTION [dbo].[testTableValueParam]
(   
    @created_date datetime = null
    ,@Ids dbo.IdList readonly
)
RETURNS TABLE 
AS
RETURN 
(
     SELECT top 10
            name
            ,scores
            ,mgr_name

        from dbo.employee
        where
           (@created_date IS NULL OR created_date = @created_date)
            and 
              ( 
                NOT EXISTS (SELECT * FROM @Ids) 
                OR
                employeeId in (select empid from @Ids)
              )            
)

试试这个。

CREATE FUNCTION [dbo].[testTableValueParam]
(   
    @created_date datetime = null
    ,@Ids dbo.IdList readonly
)
RETURNS TABLE 
AS
RETURN 
(
     IF EXISTS (SELECT 1 FROM @Ids)
     BEGIN
         SELECT TOP 10
                name
                ,scores
                ,mgr_name
            FROM dbo.employee
            WHERE created_date = @created_date
                AND employeeId in (select empid from @Ids)           --ignore this condition when @Ids is empty. 
    END
    ELSE
    BEGIN
        SELECT TOP 10
                name
                ,scores
                ,mgr_name
            FROM dbo.employee
            WHERE created_date = @created_date
    END
)
CREATE FUNCTION [dbo].[testTableValueParam]
(   
    @created_date datetime = null
    ,@Ids dbo.IdList readonly
)
RETURNS TABLE 
AS
RETURN 
(
     SELECT top 10
            name
            ,scores
            ,mgr_name
    from dbo.employee
    where
        created_date = @created_date
        and 
        ((select count(*) from @Ids) < 1  or  employeeId in (select empid from @Ids))
        employeeId in (select empid from @Ids)           --ignore this condition when @Ids is empty. 

)