8

i have a code like this

create function factfind(@num integer) 
returns integer 
as
begin
if   (@num=1) then
return 1;
else
return(@num*factfind(@num-1));
end if;
end

errors was that, Msg 156, Level 15, State 1, Procedure factfind, Line 5 Incorrect syntax near the keyword 'then'. Msg 156, Level 15, State 1, Procedure factfind, Line 7 Incorrect syntax near the keyword 'else'. Msg 195, Level 15, State 10, Procedure factfind, Line 8 'factfind' is not a recognized built-in function name.

please help me friends.

3 Answers 3

9
...
begin
    return ( CASE
                WHEN @num=1 THEN 1
                ELSE @num * dbo.factfind(@num-1)
             END
        );
end

Edit: needs to be dbo.factfind because scalar udfs must be schema qualified

Sign up to request clarification or add additional context in comments.

1 Comment

Doesn't a CASE statement require an 'END'?
5

Execute this:

CREATE FUNCTION dbo.fakultät(@n DECIMAL(38,0))
RETURNS DECIMAL(38,0)
AS
BEGIN
DECLARE @tmp DECIMAL(38,0)
    IF (@n <= 1)
        SELECT @tmp = 1
 ELSE
  SELECT @tmp = @n * dbo.fakultät(@n - 1)
 RETURN @tmp
END

or:

CREATE FUNCTION dbo.Factorial ( @iNumber int )
RETURNS INT
AS
BEGIN
DECLARE @i  int

    IF @iNumber <= 1
        SET @i = 1
    ELSE
        SET @i = @iNumber * dbo.Factorial( @iNumber - 1 )
RETURN (@i)
END

Comments

2

The problem you have is in part the syntax of the if statement in TSQL, the right thing to do is:

create function factfind(@num integer) 
returns integer 
as 
begin 
  declare @Result int
  set @Result = 1  
  if (@num>1) 
    set @Result = @num * dbo.factfind(@num-1);
  return @Result
end 

2 Comments

Shouldn't you include an ELSE in there since you are returning twice?
the function should return a Decimal (38.0) because the results are quite large and can not be contained in an integer from 12!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.