Programing

SQL Server에 IP 주소를 저장하는 데 가장 적합한 데이터 유형은 무엇입니까?

lottogame 2020. 11. 18. 08:19
반응형

SQL Server에 IP 주소를 저장하는 데 가장 적합한 데이터 유형은 무엇입니까?


이 질문에 이미 답변이 있습니다.

SQL Server에 IPv4 주소를 저장하는 데 가장 권장되는 데이터 유형은 무엇입니까?

아니면 누군가 이미 사용자 SQL 데이터 유형 (.Net 어셈블리)을 만들었 을까요?

정렬 할 필요가 없습니다.


IPv4 주소를 binary(4) 로 저장하는 것이 가장 사실이며 서브넷 마스크 스타일 쿼리를 쉽게 할 수 있습니다. 그러나 실제로 텍스트 표현 후에는 변환이 필요합니다. 이 경우 문자열 형식을 선호 할 수 있습니다.

PARSENAME그런데 문자열로 저장하는 경우 도움이 될 수있는 거의 사용되지 않는 SQL Server 함수는 입니다. IP 주소 용으로 설계되지 않았지만 완벽하게 적합합니다. 아래 호출은 '14'를 반환합니다.

SELECT PARSENAME('123.234.23.14', 1)

(번호는 오른쪽에서 왼쪽으로).


나는 일반적으로 IPv4 주소에 varchar (15)를 사용하지만 0을 채우지 않는 한 정렬하는 것은 고통 스럽습니다.

나는 또한 과거에 그것들을 INT로 저장했습니다. IP 주소를 나타내는 4 바이트 배열로 IP 주소를 반환 System.Net.IPAddress하는 GetAddressBytes메서드가 있습니다. 다음 C # 코드를 사용하여 IPAddressint...

var ipAsInt = BitConverter.ToInt32(ip.GetAddressBytes(), 0);

나는 중복 주소를 많이 검색해야했고 인덱스가 가능한 한 작고 빠르기를 원했기 때문에 그것을 사용했습니다. 그런 다음 주소를 int IPAddress에서 .net 객체 로 다시 가져 오려면 GetByteson 메서드를 사용 BitConverter하여 int를 바이트 배열로 가져옵니다. 해당 바이트 배열을 생성자 에 전달 IPAddress하면 바이트 배열을 사용하고 IPAddress시작했던로 백업을 끝 냅니다.

var myIp = new IPAddress(BitConverter.GetBytes(ipAsInt));

수락 된 답변 의이 의견에 대해

0을 채우지 않는 한 정렬하는 것은 고통 스럽습니다.

다음은 SQL Server 2008의 트릭입니다 ( 이 책의 Itzik Ben-Gan에서 제공 ).

with ip_addresses as
(
SELECT '131.33.2.201' AS ip_address UNION ALL
SELECT '2.12.4.4' AS ip_address UNION ALL
SELECT '131.33.2.202' AS ip_address UNION ALL
SELECT '2.12.4.169' AS ip_address UNION ALL
SELECT '131.107.2.201' AS ip_address 
)
select ip_address
from ip_addresses
ORDER  BY CAST('/' + ip_address + '/' AS hierarchyid)

보고

ip_address
-------------
2.12.4.4
2.12.4.169
131.33.2.201
131.33.2.202
131.107.2.201

내가 가장 좋아하는 기사 중 하나는 IP 주소를 구문 분석하기 위해 정규식을 사용하지 않아야하는 이유에 대해 설명합니다. 그들이 말하는 대부분의 내용은 IP 주소의 텍스트 표현에 매우주의해야하는 이유를 설명하는 것입니다. 데이터베이스에서 사용할 데이터 유형을 결정하기 전에 읽어 보는 것이 좋으며 앱을 처리 할 때 수행 할 작업에 대해서도 읽어 보는 것이 좋습니다 (이 기사는 Perl에 대해 작성되었지만 모든 언어에 유용합니다).

결국 32 비트 데이터 유형 (또는 4 개의 8 비트 데이터 유형)이 최선의 선택이라고 생각합니다.


IPV4? int? 또는 tinyint x 4?

그것은 단순히 저장 및 검색인지 또는 범위 검색 기준이 될 것인지에 달려 있습니다.


IPv6를 잊지 마세요. 저장해야하는 경우 더 많은 공간이 필요합니다. 128 비트는 IPv4의 32 비트와 비교됩니다.

사람에게 친숙한 버전으로 번역하려면 도우미 코드가 필요하지만 bigint를 사용하겠습니다.


나는 여기에서 비슷한 질문을 많이 읽고 있는데,이 질문에 대한 답 중 어느 것도 다른 것의 가장 큰 대답을 언급하지 않습니다. "IPv4 주소의 경우 서명되지 않은 int로 저장하고 INET_ATON () 및 INET_NTOA () 함수는 숫자 값에서 IP 주소를 반환하며 그 반대의 경우도 마찬가지입니다. " 위에서 언급 한 php 함수를 사용하기로 결정하지 않는 한, 이것이 제 db에서 함께 갈 것이라고 생각합니다.


가장 좋은 방법 (정렬 및 IP에 대한 기타 제어가 필요하지 않은 경우)은 int 로 저장하는 것입니다. varchar 등으로 저장하면 단순한 순수 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 of 0xffffffff which equals to 255.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:


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.


I've had some success with making four smallint (or whatever smallish integer datatype you prefer) columns -- one for each octet. Then, you can make a view which smashes them together as a char string (for display) or then you can write simple operators to determine who all is in what subnet etc.

It is quite fast (provided you do proper indexing) and also allows for really easy querying (no string manipulation!).


Since an IP address has 32 bits in it, can you just use a LONG to store the numerical value?
It wouldn't be as space-wasteful as using VARCHAR, but then you'd have to decode it back to an IP before you use it, every time, and the delay and overhead that costs might not be worth it.


The most appropriate data type for storing an IPv4 address in an MSSQL database, is an int. The only fiddly bit is converting it back to the dotted notation for display/sorting, hence I recommend you create a view that automates this for you.


I'd probably go with a varchar or char.

And set the size to 15.


Quoting this:

Store IP addresses in a CHAR(15) column. Depending on how much data you're storing, this can be quite wasteful (why do we need to store the dots?). I


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 -

function ip_convert() {
    $ip = $_SERVER['REMOTE_ADDR'];
    $intip = str_replace(".","0",$ip);
    return $intip;
}

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.

참고URL : https://stackoverflow.com/questions/1038950/what-is-the-most-appropriate-data-type-for-storing-an-ip-address-in-sql-server

반응형