0

I creating a function and I have a red error line under the BEGIN keyword and I can't figure out what is wrong with this query?

USE PR
GO

CREATE FUNCTION fnInsCosts
    (@NoDependents int)
RETURNS TABLE
BEGIN
    RETURN 
        (SELECT 
             EmpName, 
             SUM(BaseCost) AS TotBaseCost, 
             SUM(SpouseIns) AS TotSpouseCost, 
             SUM(DepIns) AS TotDepCost, 
             SUM(DentalCost) AS TotDentalCost,
             SUM(SUM(BaseCost) + SUM(SpouseIns) + SUM(DepIns) + SUM(DentalCost)) AS TotalInsCost
         FROM 
             vwPayroll
         WHERE 
             Dependants = @NoDependents
         GROUP BY 
             EmpName)
END;
4
  • For one thing, stored functions should always have the schema qualifier - e.g. CREATE FUNCTION dbo.fnInsCosts - including when you're calling them Commented Apr 17, 2020 at 4:38
  • Is this a new practice? My textbook which is sql server 2016 doesn't show it written this way? Commented Apr 17, 2020 at 4:40
  • No - well established, long time best practice - nothing new Commented Apr 17, 2020 at 4:42
  • You missed the AS keyword. That was the problem Commented Apr 17, 2020 at 4:52

1 Answer 1

1

try

CREATE FUNCTION dbo.fnInsCosts
    (@NoDependents int)
RETURNS TABLE
AS
RETURN (
    SELECT EmpName, SUM(BaseCost) AS TotBaseCost, SUM(SpouseIns) AS TotSpouseCost
        , SUM(DepIns) AS TotDepCost, SUM(DentalCost) AS TotDentalCost
        , SUM(SUM(BaseCost) + SUM(SpouseIns) + SUM(DepIns) + SUM(DentalCost)) AS TotalInsCost
    FROM vwPayroll
    WHERE Dependants = @NoDependents
    GROUP BY EmpName
)
Sign up to request clarification or add additional context in comments.

6 Comments

This seemed to work? Why would it though I've written a few of these functions like my OP and no issues?
did you try it?
Msg 130, Level 15, State 1, Procedure fnInsCosts, Line 8 [Batch Start Line 9] Cannot perform an aggregate function on an expression containing an aggregate or a subquery. Msg 208, Level 16, State 1, Line 23 Invalid object name 'dbo.fnInsCosts'.
Ok sorry you are right thank you!. You mind helping with this one though lol, I'm pretty confused, and don't want to waste all my questions
it's to do with your SUM(SUM()) . not sure why you're doing a SUM of a SUM. try getting rid of that and see how you go.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.