Porting from MySql to T-Sql. Any INET_ATON() equivalent?

前端 未结 4 888
名媛妹妹
名媛妹妹 2020-12-10 18:16

Need to move some code from MySql to TSql. I have a couple of calls to INET_ATON which converts a string which resembles an IPAddress into a number. Is there a T-SQL equival

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-10 18:36

    Little better. It uses int (4b) instead of bigint (8b). Your result should only be four bytes... one per octet:

    create function INET_ATON (@ip varchar(15))
    returns int
    begin
        declare @rslt int 
        -- This first part is a little error checking
        -- Looks for three dots and all numbers when not dots 
        if len(@ip) - len(replace(@ip,'.','')) = 3 
            AND
                isnumeric(replace(@ip,'.','')) = 1
        begin 
        set @rslt = convert(int,
                convert(binary(1),convert(tinyint,parsename(@ip, 4)))
            +   convert(binary(1),convert(tinyint,parsename(@ip, 3)))
            +   convert(binary(1),convert(tinyint,parsename(@ip, 2)))
            +   convert(binary(1),convert(tinyint,parsename(@ip, 1)))
            )
        end
        else set @rslt = 0
        return @rslt
    end;
    

提交回复
热议问题