SQL Server:如何调用UDF(如果可用)?

时间:2010-04-01 19:05:47

标签: sql-server case conditional-execution

大多数系统都有可用的用户定义函数(UDF)。有些人不会。我想使用UDF,如果它在那里:

SELECT 
    Users.*,
    dbo.UserGroupMembershipNames(Users.UserID) AS MemberOfGroupNames
FROM Users

否则回退到可接受的替代

SELECT
   Users.*,
   (SELECT TOP 1 thing FROM Something 
    WHERE Something.ID = Users.UserID) AS MemberGroupNames
FROM Users

怎么办?


我的第一次尝试,使用明显的解决方案,当然失败了:

SELECT 
    Users.*,
    CASE
    WHEN (OBJECT_ID('dbo.UserGroupMembershipNames') IS NOT NULL) THEN
           dbo.UserGroupMembershipNames(Users.UserID)
    ELSE (SELECT TOP 1 thing FROM Something 
          WHERE Something.ID = Users.UserID)
    END AS MemberOfGroupNames
FROM Users

出于我之外的原因

2 个答案:

答案 0 :(得分:2)

您可能必须首先检查该功能的存在,然后选择是否调用它:

IF OBJECT_ID('dbo.UserGroupMembershipNames') IS NOT NULL
    SELECT 
        Users.*,
        dbo.UserGroupMembershipNames(Users.UserID) AS MemberOfGroupNames
    FROM Users
ELSE
    SELECT
        Users.*,
        (SELECT TOP 1 thing FROM Something 
         WHERE Something.ID = Users.UserID) AS MemberGroupNames
    FROM Users

我不相信可以将它捆绑在单个条件SELECT语句中。

答案 1 :(得分:2)

这是因为引擎正在尝试绑定到UDF,无论是在解析还是准备执行计划期间。

您将不得不将其拆分为带有条件的两个语句(不幸的是,这显然不适用于视图或内联表值函数):

IF (OBJECT_ID('dbo.UserGroupMembershipNames') IS NOT NULL)
SELECT  
    Users.*, 
    dbo.UserGroupMembershipNames(Users.UserID) 
    AS MemberOfGroupNames 
FROM Users 
ELSE
SELECT  
    Users.*, 
    (SELECT TOP 1 thing FROM Something  
          WHERE Something.ID = Users.UserID) 
    AS MemberOfGroupNames 
FROM Users