UDF( User Defined Function) to get the count of employees under a given department

Bandi
Posted by Bandi under Sql Server category on | Points: 40 | Views : 363
CREATE FUNCTION dbo.fn_TotalEmps (@p_deptid int)
RETURNS INT
BEGIN
DECLARE @v_count INT = 0
SELECT @v_count = COUNT(*) FROM employees WHERE department_id = @p_deptid
RETURN @v_count
ENd
GO
SELECT DISTINCT DEPARTMENT_ID, DBO.fn_TotalEmps(DEPARTMENT_ID) FROM employees
GO


Here, we are passing @p_deptid as input parameter to pass department ID

'SELECT @v_count = COUNT(*) FROM employees WHERE department_id = @p_deptid'
The above statement returns the number of employees under given department...

Comments or Responses

Login to post response