HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Why can't I call my UDF directly? Why do I need to qualify it 3 levels deep?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
whycanneedqualifycalldeeplevelsdirectlyudf

Problem

I just created a UDF and testing it I found only works when I use this syntax

SELECT [PMIS].[dbo].[fnIsReportingTo] (50,1132)


I was expecting it to work like this:

select * from fnIsReportingTo (50,1132)


or

select fnIsReportingTo (50,1132)


here is my create SQL:

create function fnIsReportingTo
(
@BossID int,
@EmployeeID int)
RETURNs bit
AS
begin
declare @ret bit
    if exists (select * from dbo.fnGetEmployeeHierarchy(@BossID) where employeeID=@employeeID)
        select @ret=1
    else
        select @ret=0
return @ret
end

Solution

Scalar UDFS must be qualified with schema. You don't need the database part of the qualified name unless it's in a different database of course.

SELECT [dbo].[fnIsReportingTo] (50,1132)


In the FROM clause, you can only use table valued functions

See "Types of Functions" in MSDN

Edit: As an observation, I'd tend to avoid:

  • nesting UDFs this



  • using table lookups in scalar UDFs



if you use this function for each row of another table you have a cursor that iterates over the table in the UDF for every outer row

Even this is better. It's now table valued and expands like a view.

create function fnIsReportingTo (
    @BossID int,
    @EmployeeID int)
RETURNs table
AS
return (
      select CAST(COUNT(*) AS bit) AS FooBar
      from dbo.fnGetEmployeeHierarchy(@BossID)
     where employeeID=@employeeID)
GO

Code Snippets

SELECT [dbo].[fnIsReportingTo] (50,1132)
create function fnIsReportingTo (
    @BossID int,
    @EmployeeID int)
RETURNs table
AS
return (
      select CAST(COUNT(*) AS bit) AS FooBar
      from dbo.fnGetEmployeeHierarchy(@BossID)
     where employeeID=@employeeID)
GO

Context

StackExchange Database Administrators Q#1221, answer score: 8

Revisions (0)

No revisions yet.