How to select the last segment of an IP address?

  • Hello there,

    Say ColumnA has a value of '192.168.0.27' how could i select the 27 in its own column?

    i'm guessing some clever trick with charindex and substring? or perhaps a custom function to split the value? argh, there has to be a more efficient way of doing it.

    Knock Knock, Who's There?, sp underscore, sp underscore who?
    spid1, spid2, spid3....

  • Hey,

    Try this

    DECLARE @s-2 VARCHAR(100)

    SET @s-2 = '192.168.0.27'

    SELECT SUBSTRING(@s, LEN(@s) - CHARINDEX('.', REVERSE(@s)) + 2, LEN(@s))

    Regards,
    Nitin

  • Another possiblitity is this:

    DECLARE @ip_part VARCHAR(15)

    SET @ip_part = '192.168.0.27'

    SELECT PARSENAME(@ip_part, 1)

    [font="Verdana"]Markus Bohse[/font]

  • parsename!!!!!!!!!!!!! how have i never come accross this function before?!?! Cheers for that!

    Following now works perfect:

    SELECT BRANCH_NO,

    BRANCH_STARTRANGE,

    PARSENAME(BRANCH_STARTRANGE,4) + '.' +

    PARSENAME(BRANCH_STARTRANGE,3) + '.' +

    PARSENAME(BRANCH_STARTRANGE,2) + '.' +

    CAST(CAST(PARSENAME(BRANCH_STARTRANGE,1) AS INT) + 31 AS VARCHAR) AS BRANCH_ENDRANGE

    FROM TBL_BRANCHDETAILS

    Thanks again

    Regards

    Jordon

    Knock Knock, Who's There?, sp underscore, sp underscore who?
    spid1, spid2, spid3....

  • jordonpilling (1/13/2009)


    parsename!!!!!!!!!!!!! how have i never come accross this function before?!?! Cheers for that!

    Following now works perfect:

    SELECT BRANCH_NO,

    BRANCH_STARTRANGE,

    PARSENAME(BRANCH_STARTRANGE,4) + '.' +

    PARSENAME(BRANCH_STARTRANGE,3) + '.' +

    PARSENAME(BRANCH_STARTRANGE,2) + '.' +

    CAST(CAST(PARSENAME(BRANCH_STARTRANGE,1) AS INT) + 31 AS VARCHAR) AS BRANCH_ENDRANGE

    FROM TBL_BRANCHDETAILS

    Thanks again

    Regards

    Jordon

    Just keep in mind while using CAST/CONVERT function to convert in VARCHAR(n) and when n is not specified it defaults to 30...

    --Ramesh


  • jordonpilling (1/13/2009)


    parsename!!!!!!!!!!!!! how have i never come accross this function before?!?! Cheers for that!

    Yes, it's one of the less known function, but when it comes to working with Ip-addresses it's very usefull.

    [font="Verdana"]Markus Bohse[/font]

  • MarkusB (1/13/2009)


    Another possiblitity is this:

    DECLARE @ip_part VARCHAR(15)

    SET @ip_part = '192.168.0.27'

    SELECT PARSENAME(@ip_part, 1)

    Thanks Mark,

    I have read about this function but never thought to use for IP manipulation. 😛 I have been doing string manipulation for IPs in my all projects. 😛

    Regards,
    Nitin

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply