检查IP地址范围

Check IP address range

我尝试做IP到国家查询。

最简单的方法是这样查询:

select  Country
from    dbip
where   8 * power(255,3) +
        8 * power(255,2) + 
        8 * power(255,1) + 8
        between FromIPInt and  ToIPInt 

它适用于小 Google 的 IP,但适用于更大的 IP: 将表达式转换为数据类型 int 时出现算术溢出错误。

还有什么其他方法可以计算它?

CAST 是解决方案,但您确实把它放在了正确的位置:

select  Country
from    dbip
where   cast(255 as bigint) * power(255,3)
        +  255 * power(255,2)
        +  255 * power(255,1)
        +  255
        between FromIPInt and  ToIPInt 

如果您对整个计算进行 CAST,则会出现错误 将表达式转换为数据类型 int 的算术溢出错误:

select cast(255 * power(255,3) as bigint)    

但如果您投出第一个号码则不会

select cast(255 as bigint) * power(255,3)

更多详情:https://msdn.microsoft.com/en-us/library/ms187745.aspx

Integer constants greater than 2,147,483,647 are converted to the decimal data type, not the bigint data type.

SQL Server does not automatically promote other integer data types (tinyint, smallint, and int) to bigint.