我需要在sql中拆分ip地址。
我已经做了很多发现但找不到任何内置方法来完成任务。
我该如何完成这项任务?
我正在使用sql server
答案 0 :(得分:1)
您可以使用以下PARSENAME功能:
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函数返回对象名称的指定部分。
答案 1 :(得分:0)
我发现将IPV4地址从“点字符串”符号转换为(大)整数是有用的,这样它们就可以存储,比较,.... (请注意,以下函数不执行输入验证。)
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
转换回用零填充的虚线字符串(以便alpha排序表现良好):
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