1

我正在使用 MS SQL 20012 并有一个存储过程,代码如下:

USE [StatsAa]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[DriverVSComp] 
    -- Add the parameters for the stored procedure here
    @PERSON_NO nvarchar(50)
AS
    SET NOCOUNT ON;

DECLARE @weeks int = 26

;WITH Person AS (
   SELECT
     datediff(ww, DATE_GIVEN, getdate())+1 AS Week,
     AVG(CHECK_AMOUNT) AS Person_Check_Amount
   FROM CHECKS
   WHERE PERSON_NO=11  AND DATE_GIVEN >= dateadd(ww, -@weeks, getdate())
   GROUP BY datediff(ww, DATE_GIVEN, getdate()) +1
)

, Company AS (
    SELECT week,
  AVG (COMPANY_Check_Amount) AS COMPANY_Check_Amount
    FROM (
       SELECT
         datediff(ww, DATE_GIVEN, getdate())+1 AS Week,
         SUM(CHECK_AMOUNT)/COUNT(DISTINCT PERSON_NO) AS COMPANY_Check_Amount
       FROM CHECKS
       WHERE PERSON_NO<>11  AND DATE_GIVEN >= dateadd(ww, -@weeks, getdate())
       GROUP BY datediff(ww, DATE_GIVEN, getdate())+1 
    ) t
  GROUP BY Week
)

SELECT c.week
 , isnull(Person_Check_Amount,0)  Person_Check_Amount
 , isnull(Company_Check_Amount,0) Company_Check_Amount
FROM Person p
FULL OUTER JOIN Company c ON c.week = p.week
ORDER BY Week DESC

但我不断收到此错误:

Microsoft OLE DB Provider for ODBC Drivers error '80040e14' 

[Microsoft][SQL Server Native Client 11.0][SQL Server]Divide by zero error encountered. 

当我从 MSSMS 运行时,它工作正常并显示结果,但仅在我运行以下一次之后:

SET ARITHABORT OFF 
SET ANSI_WARNINGS OFF

但是当我运行页面(.asp页面)时错误仍然存​​在

我读到这是因为某些值是 Null 但我如何安全地将其放入存储过程中?没有数据被遗漏/通过/忽略非常重要,因为它具有 Null 值,因为那样它将抵消驱动程序和比较。数据和平均值。遇到 NULL 时是否可以设置零“0”或默认值?而且,我如何找到给它带来问题的列/行。

一如既往,非常感谢您提前提供的帮助!

4

1 回答 1

1

在以下两种情况之一中,您将在此表达式中得到除以零错误:1) 给定周没有记录,b) 周的所有 PERSON_NO 均为 NULL(假设该列可为空)

SUM(CHECK_AMOUNT)/COUNT(DISTINCT PERSON_NO) AS COMPANY_Check_Amount

尝试用这个替换它:

CASE WHEN COUNT(DISTINCT PERSON_NO) = 0 THEN 0
ELSE SUM(CHECK_AMOUNT)/COUNT(DISTINCT PERSON_NO) 
END AS COMPANY_Check_Amount
于 2013-07-01T17:42:13.793 回答