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.
Microsoft SQL Server 2008

Avatar of undefined
Last Comment
Soumi Chakraborty
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

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of Soumi Chakraborty

ASKER

Thank you so much eghtebas. This time it worked and now I understand the logic as well.
Microsoft SQL Server 2008
Microsoft SQL Server 2008

Microsoft SQL Server 2008 is a suite of relational database management system (RDBMS) products providing multi-user database access functionality.Component services include integration (SSIS), reporting (SSRS), analysis (SSAS), data quality, master data, T-SQL and performance tuning. Major improvements include the Always On technologies and support for unstructured data types.

50K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo