Tuesday, February 15, 2011

SQL Server: Store and Retrieve IP Address

We can store IP addresses in SQL Server in a varchar column. However to retrieve IP address for a specific range, we need to split each part and compare it.

Consider the following table:

image_thumb%5B2%5D.png?imgmax=800

Suppose we want to retrieve all the IP addresses that fall in the range from 192.168.120.120
to 192.168.200.255. The following query will retrieve these IP addresses:

image_thumb%5B6%5D.png?imgmax=800

Here’s the same query for you to try out:
declare @from_ip varchar(20), @to_ip varchar(20)
select @from_ip='192.168.120.120',@to_ip='192.168.200.255'
select * from @t
where
parsename(Ip_address,4)*1>= parsename(@from_ip ,4)*1 and
parsename(Ip_address,4)*1<= parsename(@to_ip ,4)*1
and
parsename(Ip_address,3)*1>= parsename(@from_ip ,3)*1 and
parsename(Ip_address,3)*1<= parsename(@to_ip ,3)*1
and
parsename(Ip_address,2)*1>= parsename(@from_ip ,2)*1 and
parsename(Ip_address,2)*1<= parsename(@to_ip ,2)*1
and
parsename(Ip_address,1)*1>= parsename(@from_ip ,1)*1 and
parsename(Ip_address,1)*1<= parsename(@to_ip ,1)*1

Read more: SQL Server curry