Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
ganatra.neha
Starting Member
30 Posts |
Posted - 2007-10-29 : 16:22:36
|
| I have written a stored procedure code for factorial of a numberError is when i execute and put a negative number or o it shows the correct answer but when i enter a positive number the result shows nullAny idea where i have gone wrong in the codefollowing is my codeALTER PROC [dbo].[Factorial] @number decimal(38,0), @factorial decimal(38,0) OUTASDECLARE @a decimal(38,0)IF (@number<0) BEGIN Print('Can''t calculate negative factorials') ENDIF (@number<2) BeginSET @factorial=1 End ELSE IF (@number>2) Set @a =1BeginWhile @a =@numberSET @a =@a+1SET @factorial= @factorial * @aEND__________________________________________Declare @factorial decimal (38,0)Execute Factorial 4, @factorial output Select @factorial |
|
|
tm
Posting Yak Master
160 Posts |
Posted - 2007-10-29 : 16:33:32
|
| Your problem is here ..IF (@number>2) << 4 is greater than 2Set @a =1 << Execute this line @a now equals 1BeginWhile @a =@number << Never go into while loop since (@a is 1) <> (@number is 4)SET @a =@a+1SET @factorial= @factorial * @aEND |
 |
|
|
tm
Posting Yak Master
160 Posts |
Posted - 2007-10-29 : 16:35:59
|
| Sorry Missed a bit ..SET @factorial= @factorial * @a << @factorial is null therefore (NULL * 1) = NULLYou need to initialise @factorial when @number > 0 or something |
 |
|
|
ganatra.neha
Starting Member
30 Posts |
Posted - 2007-10-29 : 17:00:36
|
| I have tried changing the code as follows but still the same problem persistsALTER PROC [dbo].[Factorial] @number decimal(38,0), @factorial decimal(38,0) OUTASDECLARE @a decimal(38,0)IF (@number<0) BEGIN Print('Can''t calculate negative factorials') ENDIf (@number<2) BeginSET @factorial=1 EndELSE While @number = 1Set @factorial =1 SET @a = @number - 1 SET @factorial= @factorial * @aWhat should i do to star the loop |
 |
|
|
klo
Starting Member
7 Posts |
Posted - 2007-10-29 : 17:04:59
|
| [code]IF (@number>2) << 4 is greater than 2Set @a =1 << Execute this line @a now equals 1BeginWhile @a = @number << Never go into while loop since (@a is 1) <> (@number is 4)SET @a =@a+1[/code]... sort out you're BEGIN/END blocks etc |
 |
|
|
|
|
|