SQL函数返回错误的值

时间:2010-07-14 13:39:41

标签: sql-server tsql user-defined-functions

我有一个带有2个参数的函数:@iEmployeeID@dDate

它的目的是找到给定参数的预算率。换句话说,它应该找到最大日期小于或等于@dDate参数,并返回对应的速率。

预算费率为:

Start        Rate
-------      -----
01-01-2008   600
01-01-2009   800
01-01-2010   700
DECLARE @result decimal(38,20)

SELECT @result = decRate
FROM BudgetRates BR
WHERE BR.iRefEmployeeID = @iEmployeeID
GROUP BY decRate
HAVING MAX(BR.dStart) <= @dDate

RETURN @result

  • 当提供参数06-06-2008时,它正确返回600.
  • 提供参数03-03-2009时,它正确返回800
  • 当提供参数02-02-2010时,它应返回700.该函数实际返回800。

错误在哪里?

寻找虫子: 如果我调整数字,如果它有两个可供选择的值,它似乎选择最大的费率。

4 个答案:

答案 0 :(得分:4)

肯定你的代码根本不应该分组?

SELECT TOP 1 @result = decRate
FROM BudgetRates BR
WHERE BR.iRefEmployeeID = @iEmployeeID
AND BR.dStart <= @dDate
ORDER BY BR.dStart DESC

RETURN @result

答案 1 :(得分:1)

您应该使用TOP 1选择前1来获取ORDER BY

的相应内容
DECLARE @result decimal(38,20)

SELECT TOP 1 @result = decRate
FROM BudgetRates BR
WHERE BR.iRefEmployeeID = @iEmployeeID
ORDER BY decRate DESC

RETURN @result

答案 2 :(得分:1)

好像你应该在这里使用排名功能。

DECLARE @result decimal(38,20)

SELECT @result = decRate 
(
  SELECT decRate, ROW_NUMBER() OVER (ORDER BY BR.dStart DESC) rownum
  FROM BudgetRates BR
  WHERE BR.iRefEmployeeID = @iEmployeeID
  AND BR.dStart <= @dDate
) sub
WHERE rownum = 1

RETURN @result

答案 3 :(得分:0)

尝试这个伴侣:

select @result = decRate
    from BudgetRates
      inner join (
       select max(BR.dStart) as MaxDate
       from BudgetRates
      where BR.dStart <= @dDate
        and BR.iRefEmployeeID = @iEmployeeID
                 ) temp on tmep.MaxDate = BudgetRates.dStart
                   and BudgetRates.iRefEmployeeID = @iEmployeeID