我有一个存储过程,它根据参数计算几个值的平均值。
以下是代码片段:
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT
@valFound = AVG(FilterSurface)
FROM
[tblVAR_FilterSurface]
WHERE
refDate >= DATEADD(DAY, -30, @refDate)
AND refDate <= DATEADD(DAY, 0, @refDate)
AND patientId = @patientId
INSERT INTO __TEMP(PatientId, RefDate, ModifyDate, FilterSurface)
VALUES(@patientId, @refDate, @modifyDate, @valFound);
SET @valFound = NULL
FETCH NEXT FROM db_cursor INTO @patientId, @refDate, @modifyDate
END
有时此存储过程会失败,因为系统会尝试计算NULL值的平均值并将结果分配给@valFound
变量。我认为问题是将结果分配给变量。
如何修改存储过程以正确处理空值?
答案 0 :(得分:2)
将select更改为@valFound = avg(isnull(FilterSurface,0))或将where子句更改为include并且FilterSurface不为null,具体取决于您是否要将空值计为零或排除它们