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.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 cannot see the output

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 number

Error 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 null

Any idea where i have gone wrong in the code

following is my code

ALTER PROC [dbo].[Factorial] @number decimal(38,0)
, @factorial decimal(38,0) OUT
AS
DECLARE @a decimal(38,0)

IF (@number<0)
BEGIN
Print('Can''t calculate negative factorials')
END
IF (@number<2)
Begin
SET @factorial=1
End
ELSE
IF (@number>2)
Set @a =1
Begin
While @a =@number
SET @a =@a+1
SET @factorial= @factorial * @a
END
__________________________________________
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 2
Set @a =1 << Execute this line @a now equals 1
Begin
While @a =@number << Never go into while loop since (@a is 1) <> (@number is 4)
SET @a =@a+1
SET @factorial= @factorial * @a
END
Go to Top of Page

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) = NULL

You need to initialise @factorial when @number > 0 or something
Go to Top of Page

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 persists


ALTER PROC [dbo].[Factorial] @number decimal(38,0)
, @factorial decimal(38,0) OUT
AS
DECLARE @a decimal(38,0)

IF (@number<0)
BEGIN
Print('Can''t calculate negative factorials')
END
If (@number<2)
Begin
SET @factorial=1
End
ELSE

While @number = 1
Set @factorial =1
SET @a = @number - 1
SET @factorial= @factorial * @a

What should i do to star the loop
Go to Top of Page

klo
Starting Member

7 Posts

Posted - 2007-10-29 : 17:04:59
[code]
IF (@number>2) << 4 is greater than 2
Set @a =1 << Execute this line @a now equals 1
Begin
While @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
Go to Top of Page
   

- Advertisement -