IP 地址在联结表中以 192.168.0.1 - 192.168.0.254 格式存储在 Access 数据库中作为文本值。
连接表,例如区域
Name IPAddress
Area1 192.168.0.1 - 192.168.0.254
Area2 192.168.1.1 - 192.168.1.254
我需要能够搜索这些范围之间的记录,例如
SELECT * FROM devices WHERE ipaddress = 192.168.0.1 /Returns record Name1
或
SELECT * FROM tablename WHERE ipaddress BETWEEN 192.168.0.1 AND 192.168.0.25 /Returns record Name1,Name2,Name3,etc
最佳答案
一个成功的方法由三部分组成:
解析
IPAddress
列并将其拆分为两个逻辑(文本)列:捕获范围的IPAddressLow
和IPAddressHigh
一个区域的IP。我们称其为qryAreas
:select [Name] , ... as IPAddressLow , ... as IPAddressHigh from Areas
实现一个函数(在 VBA 中,然后您可以从 Access SQL 中调用该函数)对 IP 地址进行比较。比较器函数可能是这样的:
' Returns: ' -1 if IP1 < IP2 ' 0 if IP1 = IP2 ' 1 if IP1 > IP2 Function CompareIPAddresses(ip1 As String, ip2 As String) As Integer ip1_arr = Split(ip1, ".") ip2_arr = Split(ip2, ".") For i = 0 To 3 ip1_arr(i) = CLng(ip1_arr(i)) ip2_arr(i) = CLng(ip2_arr(i)) Next i If ip1 = ip2 Then retval = 0 ElseIf ip1_arr(0) < ip2_arr(0) Then retval = -1 ElseIf ip1_arr(0) = ip2_arr(0) And ip1_arr(1) < ip2_arr(1) Then retval = -1 ElseIf ip1_arr(0) = ip2_arr(0) And ip1_arr(1) = ip2_arr(1) And ip1_arr(2) < ip2_arr(2) Then retval = -1 ElseIf ip1_arr(0) = ip2_arr(0) And ip1_arr(1) = ip2_arr(1) And ip1_arr(2) = ip2_arr(2) And ip1_arr(3) < ip2_arr(3) Then retval = -1 Else retval = 1 End If CompareIPAddresses = retval End Function
在查询中使用上述函数来确定 IP 地址是否等于某个值或在某个范围内。例如,如果您有一个地址
192.168.1.100
并且想知道它在哪个区域,您可以这样做:select [Name] from qryAreas where CompareIPAddresses(IPAddressLow, '192.168.1.100') in (-1, 0) and CompareIPAddresses('192.168.1.100', IPAddressHigh) in (-1, 0)
此处的 where
子句是更优雅的 where 192.168.1.100 between IPAddressLow and IPAddressHigh
语法的笨拙等效项,因为您没有 native IP 地址数据type 及其相应的运算符——所以你要自己动手。
关于sql - IP 地址范围的 MS Access SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23693884/