Convert SQL point IP address to binary

Source: Internet
Author: User

Set ansi_nulls on
Set quoted_identifier on
Go

/**********************************
* Function: convert an IP address to a binary value.
* Date: 2009-07-27
* Author:
* Test: Select getipbinary ('2017. 0.0.1)
**********************************/

Alter function [DBO]. [getipbinary] (@ IP varchar (32 ))
Returns nvarchar (32)
As
Begin
Declare @ ipresult varchar (50) -- returned result

Declare @ IPaddress varchar (9) -- extracted IP Address

Declare @ index int -- get the index.
Declare @ Yushu varchar (10) -- Record Remainder
Declare @ Shang int -- the operator obtained after Division
Declare @ jieguo varchar (30) -- converted result
Declare @ count int
Set @ COUNT = 0
Set @ Index = patindex ('%. %', @ IP)-1
Set @ ipresult =''
While (@ index> 0)
Begin
Set @ IPaddress = substring (@ IP, 1, @ index)
Set @ jieguo =''
-- Convert to 8-bit binary
If (cast (@ IPaddress as INT) = 0)
Begin
Set @ jieguo = '000000'
End
While (cast (@ IPaddress as INT)> 0)
Begin
Set @ Yushu = @ IPaddress % 2
Set @ Shang = @ IPaddress/2
Set @ IPaddress = @ Shang
Set @ jieguo = @ Yushu + @ jieguo
End
While (LEN (@ jieguo) <> 8)
Set @ jieguo = '0' + @ jieguo
Set @ ipresult = @ ipresult + @ jieguo
Set @ IP = substring (@ IP, @ index + 2, Len (@ IP ))
Set @ COUNT = @ count + 1
If (@ count <= 2)
Set @ Index = patindex ('%. %', @ IP)-1
Else
Set @ Index = Len (@ IP)
End
Return @ ipresult
End



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.