【发布时间】:2016-03-23 11:50:14
【问题描述】:
我有一个存储ID、Name、Code、IPLow、IPHigh 的表,例如:
1, Lucas, 804645, 192.130.1.1, 192.130.1.254
2, Maria, 222255, 192.168.2.1, 192.168.2.254
3, Julia, 123456, 192.150.3.1, 192.150.3.254
现在,如果我有一个 IP 地址192.168.2.50,我该如何检索匹配的记录?
编辑
根据 Gordon 的回答(我得到了编译错误),这就是我所拥有的:
select PersonnelPC.*
from (select PersonnelPC.*,
(
cast(parsename(iplow, 4)*1000000000 as decimal(12, 0)) +
cast(parsename(iplow, 3)*1000000 as decimal(12, 0)) +
cast(parsename(iplow, 2)*1000 as decimal(12, 0)) +
(parsename(iplow, 1))
) as iplow_decimal,
(
cast(parsename(iphigh, 4)*1000000000 as decimal(12, 0)) +
cast(parsename(iphigh, 3)*1000000 as decimal(12, 0)) +
cast(parsename(iphigh, 2)*1000 as decimal(12, 0)) +
(parsename(iphigh, 1))
) as iphigh_decimal
from PersonnelPC
) PersonnelPC
where 192168002050 between iplow_decimal and iphigh_decimal;
但这给了我一个错误:
Msg 8115, Level 16, State 2, Line 1
Arithmetic overflow error converting expression to data type int.
有什么想法吗?
【问题讨论】:
-
请描述您迄今为止所做的努力以及这些努力的结果。
-
您存储了人类友好的地址文本表示,并且没有内置的比较可以理解该格式的 IP 范围语义。改用数字比较,例如How to search efficiently for IP addresses ranges?
-
一定要测试子网不只是/24的情况
-
将大值转换为 BIGINT 以避免算术溢出错误。更好的是,将其转换为 decimal(12,0) 以保持一致性。 (cast(192168002050 as decimal(12,0)))
标签: sql sql-server