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
大家好,我正在尝试使用上面的语法创建一个获得第二高工资的sql函数,但是我收到了错误:
“选择函数中包含的语句无法将数据返回给客户端。”
任何人都可以告诉我编写函数的实际语法是什么,或者只是用正确的语法将代码转回来。提前谢谢。
答案 0 :(得分:1)
我写的是使用ROW_NUMBER()
,如下所示:
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
如果你需要处理例如,这也可以很容易地进行调整。联系{切换为RANK
或DENSE_RANK
,视情况而定)TOP
和ORDER BY
方法不适合。
答案 1 :(得分: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