Home > Database > Mysql Tutorial > SQLServer bigint 转 int带符号转换函数(原创)

SQLServer bigint 转 int带符号转换函数(原创)

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-07 15:34:24
Original
1535 people have browsed it

有一个需求是要在一个云监控的状态值中 存储多个状态 (包括可同时存在的各种异常、警告状态)使用了位运算机制在一个 int型中存储 。 现在监控日志数据量非常大(亿级别)需要对数据按每小时、每天进行聚合,供在线报表使用。 状态分了3个级别:正常(0)、

有一个需求是要在一个云监控的状态值中存储多个状态(包括可同时存在的各种异常、警告状态)使用了位运算机制在一个int型中存储

现在监控日志数据量非常大(亿级别)需要对数据按每小时、每天进行聚合,供在线报表使用。
状态分了3个级别:正常(0)、警告(1)、异常(2),聚合时需要使用max选择最差的状态,就需要对状态值进行处理加上级别和状态位个数,就要借助bigint型来做运算了,

问题是再将bigint 转为 int时获取原始状态值时,SQLServer报错了:

消息 8115,级别 16,状态 2,第 1 行
将 expression 转换为数据类型 int 时出现算术溢出错误。

因为状态码中已经用到了 0x80000000, 出现了符号位的问题。
写了一个转换函数解决了。

<span>CREATE</span> <span>FUNCTION</span> <span>[</span><span>dbo</span><span>]</span>.<span>[</span><span>BigintToInt</span><span>]</span><span>
(
     </span><span>@Value</span> <span>bigint</span><span>   
)
</span><span>RETURNS</span> <span>int</span>
<span>AS</span>
<span>BEGIN</span>
     <span>--</span><span> 是否有int符号位</span>
     <span>IF</span> <span>@Value</span> <span>&</span> <span>0x80000000</span> <span></span> <span>0</span> <span>RETURN</span> <span>@Value</span> <span>&</span> <span>0xFFFFFFFF</span> <span>|</span> <span>0xFFFFFFFF00000000</span>
     <span>--</span><span> 无符号位</span>
     <span>RETURN</span> <span>@Value</span> <span>&</span> <span>0xFFFFFFFF</span>
<span>END</span>
Copy after login

 

Related labels:
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 Issues
Problem with tp6 connecting to sqlserver database
From 1970-01-01 08:00:00
0
0
0
Unable to connect to SQL Server in Laravel
From 1970-01-01 08:00:00
0
0
0
Methods of parsing MYD, MYI, and FRM files
From 1970-01-01 08:00:00
0
0
0
SQLSTATE: User login failed
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template