无符号右移'>>>' sql server

时间:2015-06-26 11:43:37

标签: sql sql-server sql-server-2008 bitwise-operators

如何在sql server中编写无符号右移运算符?表达式类似于value >>> 0

这是例如 -5381>>> 0 = 4294961915

2 个答案:

答案 0 :(得分:5)

T-SQL没有位移操作符,因此您必须自己实现一个。这里有一个按位移位的实现:http://dataeducation.com/bitmask-handling-part-4-left-shift-and-right-shift/

你必须将你的整数转换为varbinary,使用按位移位函数并转换回整数和(希望)hey-presto!有你期待的结果。

实施和测试留给读者练习......

编辑 - 为了澄清我在下面的评论中提出的内容,执行此SQL将演示各种CAST给出的不同结果:

SELECT -5381 AS Signed_Integer,
        cast(-5381 AS varbinary) AS Binary_Representation_of_Signed_Integer,
        cast(cast(-5381 AS bigint) AS varbinary) AS Binary_Representation_of_Signed_Big_Integer, 
        cast(cast(-5381 AS varbinary) AS bigint) AS Signed_Integer_Transposed_onto_Big_Integer, 
        cast(cast(cast(-5381 AS varbinary) AS bigint) AS varbinary) AS Binary_Representation_of_Signed_Integer_Trasposed_onto_Big_Integer

结果:

Signed_Integer Binary_Representation_of_Signed_Integer                        Binary_Representation_of_Signed_Big_Integer                    Signed_Integer_Transposed_onto_Big_Integer Binary_Representation_of_Signed_Integer_Trasposed_onto_Big_Integer
-------------- -------------------------------------------------------------- -------------------------------------------------------------- ------------------------------------------ ------------------------------------------------------------------
-5381          0xFFFFEAFB                                                     0xFFFFFFFFFFFFEAFB                                             4294961915                                 0x00000000FFFFEAFB

答案 1 :(得分:2)

SQL Server不支持无符号整数,因此您的值不适合INT。

您可以通过以下方式获得真正的二进制解释:

SELECT CAST(-5381 AS VARBINARY)

如果您愿意在浮点运算范围内工作,可以执行:

SELECT -5381.0 + (POWER(2, 30) * 4.0)