Splitting string using sql statement (ip address)

前端 未结 2 529
隐瞒了意图╮
隐瞒了意图╮ 2021-01-29 15:38

I need to split ip address in sql.

I have done lots of finding but could not find any builtin method that do the task.

How can I accomplish this task?

I

相关标签:
2条回答
  • 2021-01-29 16:18

    You can use PARSENAME function as following :

    with address as(
    select '192.168.1.1' as IpAddress
    Union
    select '192.168.1.2' as IpAddress
    Union
    select '192.168.1.3' as IpAddress
    )
    SELECT PARSENAME(IpAddress,4) as first, 
       PARSENAME(IpAddress,3) as second,
       PARSENAME(IpAddress,2) as third,
       PARSENAME(IpAddress,1) as fourth,
    FROM address
    

    PARSENAME function returns the specified part of an object name.

    0 讨论(0)
  • 2021-01-29 16:28

    I've found it useful to convert IPV4 addresses from "dotted string" notation to a (big) integer so that they can be stored, compared, ... . (Note that the following function does not perform input validation.)

    create function [dbo].[IntegerIPV4Address]( @IPV4Address VarChar(16) )
      returns BigInt
      with SchemaBinding -- Deterministic function.
      begin
      -- NB: ParseName   is non-deterministic.
      declare @Dot1 as Int = CharIndex( '.', @IPV4Address );
      declare @Dot2 as Int = CharIndex( '.', @IPV4Address, @Dot1 + 1 );
      declare @Dot3 as Int = CharIndex( '.', @IPV4Address, @Dot2 + 1 );
      return Cast( Substring( @IPV4Address, 0, @Dot1 ) as BigInt ) * 0x1000000 +
        Cast( Substring( @IPV4Address, @Dot1 + 1, @Dot2 - @Dot1 - 1 ) as BigInt ) * 0x10000 +  
        Cast( Substring( @IPV4Address, @Dot2 + 1, @Dot3 - @Dot2 - 1 ) as BigInt ) * 0x100 +
        Cast( Substring( @IPV4Address, @Dot3 + 1, Len( @IPV4Address ) * 1 ) as BigInt );
      end
    

    Converting back to a dotted string padded with zeroes (so that an alpha sort behaves well):

    create function [dbo].[NormalizedIPV4Address]( @IntegerIPV4Address as BigInt )
      returns VarChar(16)
      with SchemaBinding -- Deterministic function.
      begin
      declare @BinaryAddress as VarBinary(4) = Cast( @IntegerIPV4Address as VarBinary(4) );
      return Right( '00' + Cast( Cast( Substring( @BinaryAddress, 1, 1 ) as Int ) as VarChar(3) ), 3 ) +
        '.' + Right( '00' + Cast( Cast( Substring( @BinaryAddress, 2, 1 ) as Int ) as VarChar(3) ), 3 ) +
        '.' + Right( '00' + Cast( Cast( Substring( @BinaryAddress, 3, 1 ) as Int ) as VarChar(3) ), 3 ) +
        '.' + Right( '00' + Cast( Cast( Substring( @BinaryAddress, 4, 1 ) as Int ) as VarChar(3) ), 3 )
      end
    
    0 讨论(0)
提交回复
热议问题