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

上面的函数从与提供的@roleid 参数匹配的actions_roles 表中返回一个操作列表。但是,actions 表中的某些操作在 action_roles 表中根本不存在。因此,当指定 NULL 参数时,我希望函数简单地返回

select * from actions

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

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

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

4

1 回答 1

2

您可以简单地将对参数无效性的检查移至外部查询。

这应该可以满足您的要求,同时简化查询并可能使其更高效(这会更改查询计划器,使其在参数为空时不执行子查询)。

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

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

于 2020-02-16T21:58:36.153 回答