2
CREATE FUNCTION dbo.abz(@number1 INT)
RETURNS INT
WITH RETURNS NULL ON NULL INPUT
AS
BEGIN 
IF @number1 < 0 
    BEGIN 
    RETURN -1 * @number1
    END
IF @number1 = 0
    BEGIN --line21
    RETURN 0
    END
IF @number1 > 0
    BEGIN
    RETURN @number1
    END
END

I get this error when this code is run:

Msg 156, Level 15, State 1, Server DB, Procedure abz, Line 21 Incorrect syntax near the keyword 'IF'.

Why? There's not even an IF statement on that line.

2
  • 3
    I assume you have a good reason for not using the built-in abs() function, which does the same thing. Commented Apr 8, 2016 at 20:38
  • I get The last statement included within a function must be a return statement, which makes sense since not all your paths of execution return something. Commented Apr 8, 2016 at 20:39

2 Answers 2

4

SQL Server functions can have only one RETURN statement and it should be the last statement of the function. You can do that using a dummy variable. Also, line numbers are counted from the last GO statement or the start of script, including blank lines. So, Line 21 as per SQL Server might not be line 21 in your editor.

CREATE FUNCTION dbo.abz(@number1 INT)
RETURNS INT
WITH RETURNS NULL ON NULL INPUT
AS
BEGIN 
DECLARE @ret INT

IF @number1 < 0 
    BEGIN 
        SET @ret = -1 * @number1
    END
IF @number1 = 0
    BEGIN --line21
        SET @ret = 0
    END
IF @number1 > 0
    BEGIN
        SET @ret = @number1
    END
RETURN @ret
END
Sign up to request clarification or add additional context in comments.

1 Comment

"So, Line 21 as per SQL Server might not be line 21 in your editor." Thanks for your answer and thanks for this quoted part especially.
0

You should be using ABS() instead of this function. It does the exact same thing. However, to show you what you need to do for functions going forward to not get an error, I will present the rewritten function to remove the error:

CREATE FUNCTION dbo.abz(@number1 INT)
RETURNS INT
WITH RETURNS NULL ON NULL INPUT
AS
BEGIN 
IF @number1 < 0 
    BEGIN 
   set @number1 =  -1 * @number1
    END


Return   @number1 


END

Note I removed the last two if statements as they return the same value as the input variable. But the real reason your function is failing is that the very last statement of the the function must be the return, you can't use return within the if statements.

1 Comment

Thank you. Clearly, I'm new to SQL. I only used the redundant "if" statements in an attempt to figure out exactly what the problem was.

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.