我正在使用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值,因为它会偏移驱动程序和Comp。数据和平均。 当它遇到NULL时,是否可以设置零'0'或默认值? 而且,我如何找到哪个列/行给它一个问题。
一如既往,非常感谢你提前帮助!
答案 0 :(得分: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