开发者

SQL Server: How to call a UDF, if available?

开发者 https://www.devze.com 2022-12-25 03:55 出处:网络
Most systems will have a user-defined function (UDF) available. Some will not. i want to use the UDF if it\'s there:

Most systems will have a user-defined function (UDF) available. Some will not. i want to use the UDF if it's there:

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

Otherwise fallback to the acceptable alternative

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

How do?


My first attempt, using the obvious solution, of course failed:

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 Me开发者_JS百科mberOfGroupNames
FROM Users

for reasons beyond me


This is because the engine is attempting to bind to the UDF, either during the parsing or preparation of the execution plan.

You will have to split it into two statements with a conditional (obvisously this will not work in a view or inline table-valued function, unfortunately):

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 


You'd probably have to check for the existance of the function first, and then select either with or without calling it:

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

I don't believe it's possible to bundle this up in a single, conditional SELECT statement.

0

精彩评论

暂无评论...
验证码 换一张
取 消