遇到零错误 - SQL Server

时间:2017-08-22 18:51:02

标签: sql sql-server sql-server-2016 divide-by-zero dateadd

我使用以下示例代码

在SQL Server表中生成随机DateTime

示例代码:

DECLARE @SeedInt INT = 0;
SELECT DATEADD(minute,(-1 * (ABS(Checksum(NewID()) % (CASE WHEN @SeedInt IS NULL OR @SeedInt <= 0 THEN 2 ELSE @SeedInt END - 1))) + 1), SYSUTCDATETIME());

工作正常。但我在UPDATE查询中尝试了相同的方法,它无法更新并抛出异常

表架构: StudentMark

CREATE TABLE [dbo].[StudentMark]
(
    [StudentMarkId] [int] IDENTITY(1,1) NOT NULL,
    [StudentId] [uniqueidentifier] NOT NULL,
    [SubjectId] [uniqueidentifier] NOT NULL,
    [Score] [int] NOT NULL,
    [ScoreInfo] [xml] NOT NULL,
    [GeneratedOn] [datetime2](2) NOT NULL,
    [IsPass] [bit] NOT NULL,
    CONSTRAINT [PK_StudentMark] 
       PRIMARY KEY CLUSTERED ([StudentMarkId] ASC)
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

示例种子数据

INSERT INTO [dbo].[StudentMark] ([StudentId], [SubjectId], [ScoreInfo], [GeneratedOn], [Score], [IsPass])
VALUES ('FC3CB475-B480-4129-9190-6DE880E2D581', '0D72F79E-FB48-4D3E-9906-B78A9D105081', '<StudentMarkAttribute xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></StudentMarkAttribute>', '2017-08-10 10:10:15', 95, 1),
       ('0F4EF48C-93E3-41AA-8295-F6B0E8D8C3A2', '0D72F79E-FB48-4D3E-9906-B78A9D105081', '<StudentMarkAttribute xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></StudentMarkAttribute>', '2017-08-10 10:10:15', 100, 1),
       ('0F4EF48C-93E3-41AA-8295-F6B0E8D8C3A2', 'AB172272-D2E9-49E1-8040-6117BB6743DB', '<StudentMarkAttribute xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></StudentMarkAttribute>', '2017-08-16 09:06:20', 25, 0),
       ('FC3CB475-B480-4129-9190-6DE880E2D581', 'AB172272-D2E9-49E1-8040-6117BB6743DB', '<StudentMarkAttribute xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></StudentMarkAttribute>', '2017-08-16 09:06:20', 82, 1);

更新查询 :( SQL Server)

UPDATE SInfo
    SET
        GeneratedOn = DATEADD(minute,(-1 * (ABS(Checksum(NewID()) % (CASE WHEN SInfo.StudentMarkId IS NULL OR SInfo.StudentMarkId <= 0 THEN 2 ELSE SInfo.StudentMarkId END - 1))) + 1), SYSUTCDATETIME())
    FROM dbo.StudentMark AS SInfo

但是查询会抛出异常

  

Msg 8134,Level 16,State 1,Line 1   遇到零除错误。   声明已经终止。

请帮助我查询中的错误,需要采取哪些措施来解决此问题?

1 个答案:

答案 0 :(得分:1)

%操作数为0时会发生这种情况。因此,请使用NULLIF()

UPDATE SInfo
    SET GeneratedOn = DATEADD(minute,
                              (-1 * (ABS(Checksum(NewID()) % NULLIF(CASE WHEN SInfo.StudentMarkId IS NULL OR SInfo.StudentMarkId <= 0 THEN 2 ELSE SInfo.StudentMarkId END - 1), 0)) + 1)), SYSUTCDATETIME())
    FROM dbo.StudentMark SInfo;