2
CREATE FUNCTION Salary.SecondHighestSalary()

Returns int

AS 

    BEGIN
    Declare @salary int;

  SELECT TOP 1 salary FROM (

  SELECT TOP 2 salary FROM Salary
  ORDER BY salary DESC
) as maxsalary ORDER BY salary ASC

Return @salary  
END

Hello everyone, I am trying to create a sql function of getting the second highest salary by using the above syntax but i am getting the error:

"Select statements included within a function cannot return data to a client."

Can anyone please tell me what is the actual syntax to write the function or just turn my code back with the correct syntax. Thanks in advance.

2 Answers 2

1

I'd write is using ROW_NUMBER() as follows:

CREATE FUNCTION SecondHighestSalary()

Returns int

AS 
begin
    Return (
      select salary from (
         select salary,ROW_NUMBER() OVER (ORDER BY salary desc) as rn
         from Salary
        ) t
      where rn = 2);
END

This also allows it to be easily adapted if you need to deal with e.g. ties (switch to RANK or DENSE_RANK as appropriate) which the TOP and ORDER BY approach isn't so amenable to.

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

Comments

0
CREATE FUNCTION Salary.SecondHighestSalary()

Returns int

AS 

    BEGIN
    Declare @salary int;

  SELECT TOP 1 @salary = salary FROM (

  SELECT TOP 2 salary FROM Salary
  ORDER BY salary DESC
) as maxsalary ORDER BY salary ASC

Return @salary  
END

6 Comments

I am able to built function successfully, but now when I tried to execute this by using: SELECT * FROM SecondHighestSalary() It is giving error: Invalid object name 'SecondHighestSalary'. Please suggest.
You defined this in the Salary schema. Also, you have defined a scalar function, not a table-valued one, so your call syntax needs to be different. Try running select Salary.SecondHighestSalary()
No, I changed some syntax while creating my function: CREATE FUNCTION SecondHighestSalary() This is my function name and now no schema I am using. And if I call SELECT SecondHighestSalary() it gives the following error: 'SecondHighestSalary' is not a recognized built-in function name.
@user2289490 - you have to include the schema name when calling a scalar UDF. So if it's no longer in Salary, it's presumably in dbo.
Exactly you are right, I just need to write SELECT dbo.SecondHighestSalary(). But the strange thing is that I have an schema name as Salary, so when I tried using statement CREATE FUNCTION Salary.SecondHighestSalary(), it gives the following error The specified schema name "Salary" either does not exist or you do not have permission to use it.. Can you please suggest where I am doing wrong.
|

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.