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

6

我正在编写一个函数,其中我传递了一个表值参数。在某些情况下,表值参数可能为空。

因此,我的函数如下所示-

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. 
)

我的表类型如下所示-

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

我正在从C#代码中调用我的函数。
如果表值参数为空,我想忽略where子句中的条件。
在搜索答案时,我查看了一些链接,但之前的帖子中提供的答案没有解决我的问题。
所以,现在当@Ids参数为空时,它会给我返回零条记录。
在一些帖子中,他们建议根本不要传递表值参数,它会自动将其视为一个空表。
但是我有时需要传递具有数据的参数。
一些答案建议使用if exist(select 1 from @Ids)
但我无法在where子句中使用if exist。
请提供任何建议。
非常感谢您的回复。
谢谢。

一个快速的解决方法不是在进入选择语句之前检查Ids吗?如果Ids为空,则选择...没有where子句,否则选择带有where子句。 - NKD
M.Ali提供的解决方案应该可以工作。我还要指出,你有一个前10名但没有排序。这意味着顺序不总是相同的。 - Sean Lange
3个回答

20
您可以使用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)
              )            
)

1
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. 

)


-1

试试这个。

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
)

由于内联表值函数中不能有IF..ELSE块,因此答案是错误的。 - M.Ali

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接