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

大家好,我正在尝试使用上述语法创建一个获得第二高薪水的sql函数,但出现错误:

"函数中包含的 Select 语句不能将数据返回给客户端。 "

谁能告诉我编写函数的实际语法是什么,或者只是用正确的语法把我的代码转回来。提前致谢。

4

2 回答 2

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

如果您需要处理and方法不太适合的例如关系(切换到RANKDENSE_RANK酌情),这也允许它轻松调整。TOPORDER BY

于 2013-04-17T07:24:21.937 回答
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
于 2013-04-17T07:18:38.920 回答