SQL IP to BigInt

前一篇博客 IP to Integer 提供的 SQL 函数是 IP 转换成 Integer 的方法。 Integer 的最大值为: 2147483647(2^31 - 1)。按照 IP 转换成整数的算法,会算出来大于这个值的,所以之前提供的 IP 转换成 Integer 的方法会算出负值。

下面是 IP to BigInt 的转换算法, 这时候运算就不会小于零。

CREATE FUNCTION dbo.ipStringToBigInt 
( 
    @ip CHAR(15) 
) 
RETURNS bigint 
AS 
BEGIN 
    DECLARE @rv bigint, 
        @o1 bigint, 
        @o2 INT, 
        @o3 INT, 
        @o4 INT
 
    SELECT 
        @o1 = CONVERT(INT, PARSENAME(@ip, 4)), 
        @o2 = CONVERT(INT, PARSENAME(@ip, 3)), 
        @o3 = CONVERT(INT, PARSENAME(@ip, 2)), 
        @o4 = CONVERT(INT, PARSENAME(@ip, 1)) 
 
    IF (@o1 BETWEEN 0 AND 255) 
        AND (@o2 BETWEEN 0 AND 255) 
        AND (@o3 BETWEEN 0 AND 255) 
        AND (@o4 BETWEEN 0 AND 255) 
    BEGIN      
 
        SET @rv = (@o1 * 16777216)  +  
            (@o2 * 65536) +  
            (@o3 * 256) + 
            (@o4) 
    END 
    ELSE 
        SET @rv = -1 
    RETURN @rv 
END
go 



CREATE FUNCTION dbo.ipBigIntToString 
( 
    @ip bigint 
) 
RETURNS CHAR(15) 
AS 
BEGIN 
    DECLARE @o1 INT, 
        @o2 INT, 
        @o3 INT, 
        @o4 INT 
 
    IF @ip > 4294967295 RETURN '255.255.255.255' 
    IF @ip <= 0 RETURN '0.0.0.0' 
 
    SET @o1 = @ip / 16777216
 
    SET @ip = @ip % 16777216 
    SET @o2 = @ip / 65536 
    SET @ip = @ip % 65536 
    SET @o3 = @ip / 256 
    SET @ip = @ip % 256 
    SET @o4 = @ip 
 
    RETURN 
        CONVERT(VARCHAR(4), @o1) + '.' + 
        CONVERT(VARCHAR(4), @o2) + '.' + 
        CONVERT(VARCHAR(4), @o3) + '.' + 
        CONVERT(VARCHAR(4), @o4) 
END

go 

-- 调用例子
select dbo.ipBigIntToString(3708279131)
select dbo.ipStringToBigInt('221.7.217.91')

你可能感兴趣的:(sql,算法,function,Integer)