One requirement is to store multiple states in a cloud-monitored state value (including various exceptions, warning states that can exist simultaneously) using a bitwise operation mechanism to store in an int.
Now the monitoring log data is very large (billion levels) need to data per hour, daily aggregation for online report use.
The status is divided into 3 levels: normal (0), Warning (1), exception (2), aggregation needs to use the max to choose the worst state, you need to process the state value and the number of States, it is necessary to use the bigint type to do the operation,
The problem is when you get the original state value when you convert bigint to int, SQL Server complains:
Message 8115, Level 16, State 2, line 1th
An arithmetic overflow error occurred while converting expression to a data type int.
Because the 0x80000000 is already used in the status code, there is a problem with the sign bit.
A conversion function was written to solve the problem.
CREATE FUNCTION [dbo]. [Biginttoint]
(
@Value bigint
)
RETURNS int
as
BEGIN
--Is there an int symbol bit
if @Value & 0x80000000 <> 0 Return @Value & 0xFFFFFFFF | 0xffffffff00000000
--unsigned bit return
@Value & 0xFFFFFFFF End