开发者

using if statement in sql function

开发者 https://www.devze.com 2023-03-02 10:53 出处:网络
i have a code like this create function factfind(@num integer) returns integer as begin if(@num=1) then return 1;

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 frie开发者_Go百科nds.


...
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


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


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 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号