Factorial Function in SQL Server
Factorial function returns factorial of a number . i.e n*(n-1).U can change from Integer to bigint
Creating a User Defined Function called Fact
create function dbo.fact(@num1 integer)
returns int
as
begin
declare @factno int;
if (@num1=1) set @factno=1;
else
set @factno= @num1*dbo.fact(@num1-1);
return @factno;
end;
if @num1 is 1 returnreturns int
as
begin
declare @factno int;
if (@num1=1) set @factno=1;
else
set @factno= @num1*dbo.fact(@num1-1);
return @factno;
end;
otherwise calculate num1*fact(num-1);
store it temporary variable called @factno. in sql server functions last statement should be return.
Calling user defined function in T_SQL
select fact(10) "factorial"
factorial
39916800
select dbo.fact2(11) ,dbo.fact2(6)
(No column name) (No column name)
39916800 720
Tags:Factorial Function in SQL Server,
Calling user defined function in T_SQL,
Creating a User Defined Function called Fact, Factorial Function in SQL-Server,Factorial Function in T-SQL, Recursive functions in T_SQL,Recursive functions in SQL-SERVER,sql server 2012,t-sql
No comments:
Post a Comment