2

Firstly apologies - I know there are numerous threads on this subject however I can't find an answer to my question.

I have a UDF to work out business days between two dates. I am using SQL Server 2008.

CREATE FUNCTION dbo.fn_CountWeekDays
(
    @fromdate Datetime,
    @todate Datetime
)
RETURNS TABLE AS RETURN
(

SELECT
   (DATEDIFF(dd, @fromdate, @todate) + 1)
  -(DATEDIFF(wk, @fromdate, @todate) * 2)
  -(CASE WHEN DATENAME(dw, @fromdate) = 'Sunday' THEN 1 ELSE 0 END)
  -(CASE WHEN DATENAME(dw, @todate) = 'Saturday' THEN 1 ELSE 0 END)
  As NoOfWeekDays

)

I am trying to call it in a select statement along with another table:

select dbo.fn_CountWeekDays(a.date1,a.date2) as workdays
from alex_datetest a

However I am getting the error:

Cannot find either column "dbo" or the user-defined function or aggregate "dbo.fn_CountWeekDays", or the name is ambiguous.

If I drop the dbo. then I get this:

'fn_CountWeekDays' is not a recognized function name.

Does anyone have any ideas why I can't reference this function?

Thanks in advance

Alex

2
  • 1
    Your function returns a table, but you're referencing it as if it returned a scalar value. Commented Aug 3, 2017 at 10:37
  • You are using table value function, all you need it to change the RETURN to the datatype you want to use, for you it will be int Commented Aug 3, 2017 at 10:39

3 Answers 3

1

As I put in the comment, alter your function to be:

CREATE FUNCTION dbo.fn_CountWeekDays
(
    @fromdate Datetime,
    @todate Datetime
)
RETURNS int
AS
BEGIN DECLARE @int int

SET @int = 
   (DATEDIFF(dd, @fromdate, @todate) + 1)
  -(DATEDIFF(wk, @fromdate, @todate) * 2)
  -(CASE WHEN DATENAME(dw, @fromdate) = 'Sunday' THEN 1 ELSE 0 END)
  -(CASE WHEN DATENAME(dw, @todate) = 'Saturday' THEN 1 ELSE 0 END);

  RETURN @int
END
Sign up to request clarification or add additional context in comments.

Comments

0

You have a table valued function, so you want to use apply:

select cwd.*
from alex_datetest a cross apply 
     dbo.fn_CountWeekDays(a.date1,a.date2) cwd

If you want to name the column:

select cwd.workdays
from alex_datetest a cross apply 
     dbo.fn_CountWeekDays(a.date1,a.date2) cwd(workdays)

Comments

0

Since it is returning table you might require to use cross apply as below:

Select * from yourtable a
   cross apply dbo.fn_CountWeekDays(a.date1,a.date2) f

1 Comment

Thank you so much - Works perfectly. I've been puzzling over this for hours

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.