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

前端 未结 4 879
名媛妹妹
名媛妹妹 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:44

    More a different option than a direct answer to your question (I see the downvotes coming ^^), but you could also consider putting the conversion logic into your software instead of the query. Depending on language and use case this might be even better.

    Examples

    PHP: ip2long("192.168.1.1");

    C/C++: inet_addr("192.168.1.1");

    C#

    System.Net.IPAddress ip;
    long ipn = (System.Net.IPAddress.TryParse("192.168.1.1", out ip))
    
        ? (((long) ip.GetAddressBytes()[0] << 24) | (ip.GetAddressBytes()[1] << 16) |
                  (ip.GetAddressBytes()[2] <<  8) |  ip.GetAddressBytes()[3])
    
        : 0;
    

    You could also give it -1, or null (with long? as datatype), or write a method which throws an exception, in case the conversion fails.

    Python

    reduce(lambda sum, chunk: sum <<8 | chunk, map(int, '192.168.1.1'.split(".")))
    

    Before you start downvoting: This is just a short example, no error handling here, I know.

    Conclusion

    Of course it is most of the time nicer to let the dbs do the job, but it really depends, and in case you don' t have a project with millions of requests per second, this might help.

提交回复
热议问题