0

Can anyone please let me know where of the SQL query is wrong?

The error is

Incorrect syntax near "return"

Code:

CREATE FUNCTION getNthHighestSalary(@N INT) 
RETURNS INT 
AS
BEGIN
    WITH ranksalary AS
    (
        SELECT
            salary, 
            ROW_NUMBER() OVER (ORDER BY Salary DESC) AS Rank
        FROM
            Employee
    )
    RETURN (SELECT Salary AS getNthHighestSalary 
            FROM ranksalary
            WHERE Rank = @N);
END
6
  • are you missing a ; after Employee) ? Commented Dec 3, 2018 at 19:00
  • Added ":" and it still give me the error.... Commented Dec 3, 2018 at 19:11
  • 1
    This is not SQL. What language is this? Commented Dec 3, 2018 at 19:30
  • 1
    Which dbms are you using? (That code is product specific.) Commented Dec 3, 2018 at 19:36
  • 1
    You can NOT return an expression - you need to first store the value from that SELECT into a local variable in your function, and then return that variable's value. Commented Dec 3, 2018 at 19:57

2 Answers 2

1

Looks like T-SQL to me. As @marc_s already pointed out you need to store the value in a variable first and then return that.

CREATE FUNCTION getNthHighestSalary(@N INT)
RETURNS INT
AS
BEGIN
    DECLARE @result int
    ;WITH ranksalary AS
    (
        SELECT
            salary, 
            ROW_NUMBER() OVER (ORDER BY Salary DESC) AS [Rank]
        FROM
            Employee
    )
    SELECT @result = Salary
      FROM ranksalary
      WHERE [Rank] = @N

    RETURN @result
END

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

Comments

0

Why not just use this logic?

declare @rank;

select @rank = count(*) + 1
from employee
where salary > @salary;

return @rank;

Comments

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.