Select record between two IP ranges

前端 未结 8 2136
遇见更好的自我
遇见更好的自我 2021-02-19 05:14

I have a table which stores a ID, Name, Code, IPLow, IPHigh such as:

1, Lucas, 804645, 192.130.1         


        
8条回答
  •  别那么骄傲
    2021-02-19 05:29

    With this function you can transform any IP address to a form where each part has 3 digits. With this you could do a normal alphanumeric compare. if you want you could return BIGINT too...

    CREATE FUNCTION dbo.IPWidth3(@IP VARCHAR(100))
    RETURNS VARCHAR(15)
    BEGIN
    DECLARE @RetVal VARCHAR(15);
    WITH Splitted AS
    (
        SELECT CAST('' + REPLACE(@IP,'.','') + '' AS XML) AS IPSplitted 
    )
    SELECT @RetVal = STUFF(
            (
            SELECT '.' + REPLACE(STR(Part.value('.','int'),3),' ','0')
            FROM Splitted.IPSplitted.nodes('/x') AS One(Part)
            FOR XML PATH('')
            ),1,1,'') 
    FROM Splitted;
    
    RETURN @RetVal;
    END
    GO
    
    DECLARE @IP VARCHAR(100)='192.43.2.50';
    SELECT dbo.IPWidth3(@IP);
    

    The result

    192.043.002.050
    

    To reflect Ed Harper's comment here the same function returning a DECIMAL(12,0):

    CREATE FUNCTION dbo.IP_as_Number(@IP VARCHAR(100))
    RETURNS DECIMAL(12,0)
    BEGIN
    DECLARE @RetVal DECIMAL(12,0);
    WITH Splitted AS
    (
        SELECT CAST('' + REPLACE(@IP,'.','') + '' AS XML) AS IPSplitted 
    )
    SELECT @RetVal = 
            CAST((
            SELECT REPLACE(STR(Part.value('.','int'),3),' ','0')
            FROM Splitted.IPSplitted.nodes('/x') AS One(Part)
            FOR XML PATH('')
            ) AS DECIMAL(12,0))
    FROM Splitted;
    
    RETURN @RetVal;
    END
    GO
    
    DECLARE @IP VARCHAR(100)='192.43.2.50';
    SELECT dbo.IP_as_Number(@IP);
    

提交回复
热议问题