使用以下MSSQL Select语句在返回IPv4地址时工作正常但在DB中找到IPv6地址时脚本错误:
传递给LEFT或SUBSTRING函数的长度参数无效。
脚本:
select [column 3]
from [IPs]
where [dbo].[IP2INT]
(
RIGHT(
LEFT(
[IPBan_Log],
CHARINDEX(',', [IP_Log]) - 1
),
LEN(
LEFT(
[IP_Log],
CHARINDEX(',', [IP_Log]) - 1
)
) - CHARINDEX('ss', [IP_Log]) - 2
)
) between [Column 0] and [Column 1]
)
如何更改脚本以处理IPv6(fe80 :: d474:f998:3980:360d)以及IPv4(91.204.2121.163)?
我们的自定义功能:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER function [dbo].[IP2INT](@ipAddress varchar(20))
RETURNS bigint
AS
BEGIN
DECLARE @FirstDot int, @SecondDot int, @ThirdDot int,
@FirstOctet varchar(3), @SecondOctet varchar(3),
@ThirdOctet varchar(3), @FourthOctet varchar(3),
@Result bigint
SET @FirstDot = CHARINDEX('.', @ipAddress)
SET @SecondDot = CHARINDEX('.', @ipAddress, @FirstDot + 1)
SET @ThirdDot = CHARINDEX('.', @ipAddress, @SecondDot + 1)
SET @FirstOctet = SUBSTRING(@ipAddress, 1, @FirstDot - 1)
SET @SecondOctet = SUBSTRING(@ipAddress, @FirstDot + 1, @SecondDot - @FirstDot - 1)
SET @ThirdOctet = SUBSTRING(@ipAddress, @SecondDot + 1, @ThirdDot - @SecondDot - 1)
SET @FourthOctet = SUBSTRING(@ipAddress, @ThirdDot + 1, 3)
SET @Result = 16777216 * CAST(@FirstOctet as bigint) +
65536 * CAST(@SecondOctet as bigint) +
256 * CAST(@ThirdOctet as bigint) +
CAST(@FourthOctet as bigint)
RETURN(@Result);
END
答案 0 :(得分:1)
我看不到为tsql记录的本机ip2int函数,所以我假设你有自己的实现,它不兼容IPv6,只在它无法解析的任何地址(如IPv6)上返回NULL或类似内容。如果你愿意提供你的实现,可以看看。