SQL函数 - 将变量自身设置为随机值

时间:2014-11-24 21:44:59

标签: function tsql variables

我创建了以下函数,似乎随机将@FCST和@QTY值更改为随机选择。以下是debug中为@FCST返回错误值的程序示例。由于@FCST为9.53,我预计它将返回9.53。 enter image description here

CREATE FUNCTION dbo.LTBADJ
(@MAT VARCHAR(30),@LCUT DATE, @QS DATE,@STAT FLOAT, @MCA FLOAT)
RETURNS FLOAT
AS BEGIN
DECLARE @HD DATE
DECLARE @ED DATE
DECLARE @FCST FLOAT
DECLARE @QTY FLOAT 
DECLARE @YRS FLOAT

SET @ED = 
(SELECT TOP 1 [EO_END_DATE] FROM [dbo].[EO_LTB]
WHERE [W_PART_NUMBER] = @MAT
AND [APPROVED_DATE] <= @LCUT
ORDER BY [EO_END_DATE] DESC)
SET @HD =DATEADD(YEAR,2,@QS)
SET @FCST = (CASE WHEN @MCA <= @STAT THEN @MCA ELSE @STAT END)
SET @FCST = (CASE WHEN @FCST <.5 THEN .5 ELSE @FCST END)
SET @YRS = (DATEDIFF(DAY,@HD,@ED) + 730)/365
SET @QTY = @FCST * @YRS
SET @QTY = (CASE WHEN @ED<=@HD THEN 0 ELSE @QTY END)
RETURN @QTY
END ;

编辑:@QTY错误计算的示例 enter image description here

1 个答案:

答案 0 :(得分:1)

一切似乎都正确 - 您可以通过运行以下SQL来查看正在发生的事情。 我怀疑混淆是数字末尾的e-002e-001;那只是SQL试图显示浮点数的值;因为浮点运算如何工作,有些数字会根据你的期望稍微计算出来,然后试着让它们可读,SQL会用指数显示数字。

declare @MAT VARCHAR(30) = '50309120000W'
,@LCUT DATE = '2014-10-26'
, @QS DATE =  '2014-10-27'
,@STAT FLOAT = 9.5399999999999999e-002
, @MCA FLOAT = 9.5399999999999999e-002


DECLARE @HD DATE
DECLARE @ED DATE
DECLARE @FCST FLOAT
DECLARE @QTY FLOAT 
DECLARE @YRS FLOAT

SET @ED = 
(
    SELECT TOP 1 [EO_END_DATE] 
    FROM (SELECT '2019-02-28' [EO_END_DATE], @MAT [W_PART_NUMBER], @LCUT [APPROVED_DATE] ) X
    WHERE [W_PART_NUMBER] = @MAT
    AND [APPROVED_DATE] <= @LCUT
    ORDER BY [EO_END_DATE] DESC
)
SET @HD =DATEADD(YEAR,2,@QS)


SET @FCST = (CASE WHEN @MCA <= @STAT THEN @MCA ELSE @STAT END)
SELECT @FCST

SET @FCST = (CASE WHEN @FCST <.5 THEN .5 ELSE @FCST END)
SELECT @FCST

SET @YRS = (DATEDIFF(DAY,@HD,@ED) + 730)/365
SET @QTY = @FCST * @YRS
SELECT @FCST, @YRS, @QTY

SET @QTY = (CASE WHEN @ED<=@HD THEN 0 ELSE @QTY END)
SELECT @QTY, @ED, @HD