Posted by matt as SQL, Transact-SQL
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 intAS
Begindeclare @factorial int
if @n = 0
set @factorial = 1
else
set @factorial = @n * dbo.Factorial(@n - 1) –call it recursivelyreturn @factorial
You can then simply call it in any of your queries like:
select dbo.Factorial(6) –returns 720
Tags: mssql sample script • t-sql • user-defined function
.Net asp .net tutorial asp .net tutorial c# sample code CSS sample script database guide java sample code javascript sample code mssql sample script string reverse in C# t-sql telerik sample code user-defined function vb .net sample code visual studio tutorial
WP Cumulus Flash tag cloud by Roy Tanck requires Flash Player 9 or better.
RSS feed for comments on this post · TrackBack URI
Leave a reply