SQL Server › User Defined Functions
What is a user defined function in SQL Server, and why would you create one instead of repeating the same logic in multiple queries?
BeginnerAnswer
A user defined function lets you package a piece of reusable logic, such as a calculation or a formatting routine, into a single named object that you can call from many different queries, avoiding the need to repeat and maintain the same complex logic in multiple places throughout your codebase.
CREATE FUNCTION dbo.CalculateAge (@BirthDate DATE)
RETURNS INT
AS
BEGIN
RETURN DATEDIFF(YEAR, @BirthDate, GETDATE());
END;
SELECT Name, dbo.CalculateAge(BirthDate) AS Age FROM Customers;Real-world example A customer reporting system uses a single reusable function to calculate age from a birth date, ensuring every report across the entire application calculates age exactly the same consistent way.