SQL Server › User Defined Functions
What are the tradeoffs between implementing complex reusable business logic as a user defined function versus building it directly into application code?
AdvancedAnswer
Implementing logic as a database function keeps it centralized and consistently enforced regardless of which application or reporting tool accesses the data, but can introduce performance concerns for certain function types and makes the logic somewhat less visible to application developers, while application level logic is often easier to test and version control but risks inconsistency if multiple applications need to implement the same business rule separately.
-- Database function: centralized, consistent across all consumers
CREATE FUNCTION dbo.CalculateShippingCost (@Weight DECIMAL(10,2))
RETURNS DECIMAL(10,2)
AS BEGIN RETURN @Weight * 0.5; END;Real-world example A company debates whether to implement shipping cost calculation as a database function accessible to both their web application and their reporting tools, or duplicate the logic in each application separately, ultimately choosing the database function for consistency across all their systems.