如何在where子句中检查表值参数是否为空?

Chr*_*ina 3 sql-server parameters

我正在写一个函数,我传递一个表值参数.在某些情况下,表值参数可以为空.

所以,我的功能如下 -

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. 
)
Run Code Online (Sandbox Code Playgroud)

我的表类型创建如下 -

CREATE TYPE [dbo].[IdList] AS TABLE(
    [empid] [nvarchar](11) NULL
)
Run Code Online (Sandbox Code Playgroud)

我从ac#代码调用我的函数.
有些情况下表值参数为空,在这种情况下,当表值参数为空时,我想忽略where子句中的条件.

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

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

请提供任何建议.
非常感谢您的回复.

谢谢.

M.A*_*Ali 14

您可以使用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)
              )            
)
Run Code Online (Sandbox Code Playgroud)