Link to home
Start Free TrialLog in
Avatar of Soumi Chakraborty
Soumi Chakraborty

asked on

User Defined Function

I need to create a function which will return an average of Vacation hours based on Gender.I have written the following code:
CREATE FUNCTION fx_avgVacationHours
(@Gender varchar(50))
Returns int
AS
BEGIN
RETURN
(
SELECT  AVG (VacationHours)
  FROM HumanResources.Employee
where Gender=@Gender
)
end

Select dbo.fx_avgVacationHours(2)

But this code is returning me a NULL value.
Please let me know what wrong i am doing here.
Avatar of Mike Eghtebas
Mike Eghtebas
Flag of United States of America image

try (if Gnder column data is 1, 2, etc.):
CREATE FUNCTION fx_avgVacationHours
(@Gender int)
Returns int
AS
BEGIN
RETURN
SELECT  AVG (VacationHours)
  FROM HumanResources.Employee
where Gender=@Gender
end

Open in new window

Avatar of Soumi Chakraborty
Soumi Chakraborty

ASKER

Thanks eghtebas. The function got created but can you please explain the logic behind it? Gender is not an integer value. Moreover the select statement is giving me an error. Please help me understand the logic.
ASKER CERTIFIED SOLUTION
Avatar of Mike Eghtebas
Mike Eghtebas
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you so much eghtebas. This time it worked and now I understand the logic as well.