Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using if statement in sql function

Tags:

sql-server

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.

like image 371
anvisha Avatar asked May 02 '11 14:05

anvisha


People also ask

Can we use IF condition in SQL function?

Syntax. In the following SQL IF Statement, it evaluates the expression, and if the condition is true, then it executes the statement mentioned in IF block otherwise statements within ELSE clause is executed.

What is the IF function in SQL?

MySQL IF() Function The IF() function returns a value if a condition is TRUE, or another value if a condition is FALSE.

How do I run an IF condition in SQL?

The Transact-SQL statement that follows an IF keyword and its condition is executed if the condition is satisfied: the Boolean expression returns TRUE. The optional ELSE keyword introduces another Transact-SQL statement that is executed when the IF condition is not satisfied: the Boolean expression returns FALSE.

Can you put an if statement in a query?

The IF() function that can be used in queries is primarily meant to be used in the SELECT portion of the query for selecting different data based on certain conditions, not so much to be used in the WHERE portion of the query: SELECT IF(JQ.


2 Answers

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

like image 155
gbn Avatar answered Dec 01 '22 05:12

gbn


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
like image 27
ahoo Avatar answered Dec 01 '22 04:12

ahoo