T-SQL can be a powerful tool for developers if exploited. It allows you to programatically manipulate your data on the “database-level”. This post will show a simple T-SQL script on how to create a recursive user-defined function [UDF] that can be used application-wide via a simple query. To demonstrate, we will use one of the most common mathematical problems in which a recursive algorithm can be applied - solving for factorial.

Create a UDF

Create Function [dbo].[Factorial]
(
@n int
)
Returns int

AS
Begin

declare @factorial int

if @n = 0
set @factorial = 1
else
set @factorial = @n * dbo.Factorial(@n - 1) –call it recursively

return @factorial

You can then simply call it in any of your queries like:

select dbo.Factorial(6) –returns 720

Tags: