Home > Database > Mysql Tutorial > SQL Server DATEADD: How to Avoid Arithmetic Overflow with Large Integer Timestamps?

SQL Server DATEADD: How to Avoid Arithmetic Overflow with Large Integer Timestamps?

Mary-Kate Olsen
Release: 2024-12-29 11:11:11
Original
622 people have browsed it

SQL Server DATEADD: How to Avoid Arithmetic Overflow with Large Integer Timestamps?

DATEADD Pitfalls with Large Integers

When working with large integer timestamps, the DATEADD function in SQL Server can encounter limitations. This article explores a specific case where a large integer value causes an arithmetic overflow error.

Problem

Consider the following SQL statement, intended to convert a large JavaScript timestamp into an SQL date:

DATEADD(MILLISECOND, cast(569337307200000 as bigint) % 1000, DATEADD(SECOND, cast(569337307200000 as bigint) / 1000, '19700101'))
Copy after login

On SQL Server 2008, executing this statement results in an "Arithmetic overflow error converting expression to data type int."

Solution

The key to overcoming this error lies in breaking down the DATEADD operation into smaller chunks. By initially adding the time in larger units (e.g., seconds or minutes) and then adding the remaining milliseconds, we can avoid the overflow.

For instance, the following statement calculates the start time given a large duration (in milliseconds):

DATEADD(ms, -large_duration_ms%60000, DATEADD(minute, -large_duration_ms/60000, GETDATE()))
Copy after login

This example subtracts the minutes from the large duration first, then adds the remaining milliseconds. This approach ensures that the intermediate calculations do not overflow.

The above is the detailed content of SQL Server DATEADD: How to Avoid Arithmetic Overflow with Large Integer Timestamps?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template