This question already has an answer here:
What should be the most recommended datatype for storing an IPv4 address in SQL server?
Or maybe someone has already created a user SQL data-type (.Net assembly) for it?
I don't need sorting.
This question already has an answer here:
What should be the most recommended datatype for storing an IPv4 address in SQL server?
Or maybe someone has already created a user SQL data-type (.Net assembly) for it?
I don't need sorting.
For space efficient storage and when the values are to be processed (matched or compared to a range), I use an
int
. The IP address really is just a 32 bit value.For a simple solution where you just want to store the value to view it, I use a
varchar(15)
to store the string representation of the IP adress.Best way (when no need sorting and other control on the IPs) is store it as int, storing it as varchar etc. would cost way more performance than just a simple innocent int.
There is a property
IPAddress.Address
but it's obsolete, I don't know why, since if you don't need sorting or control over the IP classes, the best way is to store it as unsigned integer (that has a max value of0xffffffff
which equals to255.255.255.255
in decimal representation.Also the IPAddress class has a constructor that accepts a long argument.
And according to VS debugger visualizer, that IPAddress class itself stores its internal variable as one number (not byte array).
Read more on workarounds storing a unit in MS SQL Server:
I'm newbie @ php,sql , but i think fastest way to store something in sql db is to convert it to int value and save as int.
I used function in php -
And then i just replace all dots with zeros. Then if i need use this ip from sql.. if($ip == ip_convert())
But this only if you use PHP.
Regarding this comment in the accepted answer
Here's a trick for SQL Server 2008 (From Itzik Ben-Gan in this book)
Returns
I'm reading a lot of similar questions on here, and none of the replies in this one mention the number one answer in others: "For IPv4 addresses, you may want to store them as an int unsigned and use the INET_ATON() and INET_NTOA() functions to return the IP address from its numeric value, and vice versa." I think this is what I'm going to go with in my db, unless I decide to use the php functions mentioned above.
Storing an IPv4 address as a
binary
(4) is truest to what it represents, and allows for easy subnet mask-style querying. However, it requires conversion in and out if you are actually after a text representation. In that case, you may prefer a string format.A little-used SQL Server function that might help if you are storing as a string is
PARSENAME
, by the way. Not designed for IP addresses but perfectly suited to them. The call below will return '14':(numbering is right to left).