Select record between two IP ranges

前端 未结 8 2459
遇见更好的自我
遇见更好的自我 2021-02-19 05:14

I have a table which stores a ID, Name, Code, IPLow, IPHigh such as:

1, Lucas, 804645, 192.130.1         


        
8条回答
  •  旧时难觅i
    2021-02-19 05:29

    Painfully. SQL Server has lousy string manipulation functions. It does, however, offer parsename(). This approach converts the IP address to a large decimal value for the comparison:

    select t.*
    from (select t.*,
                 (cast(parsename(iplow, 4)*1000000000.0 as decimal(12, 0)) +
                  cast(parsename(iplow, 3)*1000000.0 as decimal(12, 0)) +
                  cast(parsename(iplow, 2)*1000.0 as decimal(12, 0)) +
                  cast(parsename(iplow, 1) as decimal(12, 0))
                 ) as iplow_decimal,
                 (cast(parsename(iphigh, 4)*1000000000.0 as decimal(12, 0)) +
                  cast(parsename(iphigh, 3)*1000000.0 as decimal(12, 0)) +
                  cast(parsename(iphigh, 2)*1000.0 as decimal(12, 0)) +
                  cast(parsename(iphigh, 1) as decimal(12, 0))
                 ) as iphigh_decimal
          from t
         ) t
    where 192168002050 between iplow_decimal and iphigh_decimal;
    

    I should note that IP addresses are often stored in the database as the 4-byte unsigned integers. This makes comparisons much easier . . . although you need complicated logic (usually wrapped in a function) to convert the values to a readable format.

提交回复
热议问题