Return 传递 NULL 参数时通过 Table 函数的所有记录

Return All Records through a Table Function When NULL Parameter is Passed

CREATE FUNCTION [dbo].[fn_actions]
(
  @roleid varchar(36)
)
RETURNS TABLE
AS
RETURN
  select *
  from actions 
  where action_type_id in (
    select action_type_id
    from action_roles
    where role_id = isnull(@roleid,role_id)
  )

上面的函数 return 是 actions_roles table 中与提供的 @roleid 参数相匹配的操作列表。但是,table中的一些动作在action_rolestable中根本不存在。因此,当指定 NULL 参数时,我希望函数简单地 return

select * from actions

我尝试使用 if 语句,但这似乎不适用于内联 table 函数。

CREATE FUNCTION [dbo].[fn_actions]
(
  @roleid varchar(36)
)
RETURNS TABLE
AS
RETURN
  IF (@roleid is NULL)
  BEGIN
    select * from actions
  END
  ELSE
    select *
    from actions 
    where action_type_id in (
      select action_type_id
      from action_roles
      where role_id = isnull(@roleid,role_id)
    )

实现此目标的最佳方法是什么?

您可以简单地将对参数是否为空的检查移至外部查询。

这应该做你想做的,同时简化查询并可能使其更高效(这改变了查询计划器,使其在参数为 null 时不执行子查询)。

select * 
from actions 
where 
    @roleid is null
    or action_type_id in (select action_type_id from action_roles)

注意:正如 Vladimir Baranov 评论的那样,您可能应该将 option(recompile) 添加到此查询(它在最后),以强制数据库为每次执行重新计算查询计划,因此它可以当参数为 null 时,可能会优化子查询。