Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm working on a function to convert the string representation of an IP into its varbinary(4/16) form.

Right now, I have this:

@stringIP = ''
    CAST(PARSENAME(@stringIP, 4) as tinyint),
    CAST(PARSENAME(@stringIP, 3) as tinyint),
    CAST(PARSENAME(@stringIP, 2) as tinyint),
    CAST(PARSENAME(@stringIP, 1) as tinyint)

This breaks up my IPv4 Address very well; but I need to figure out how to insert it into a varbinary(4) so I can insert the data to my table. I cannot find ANY TSQL syntax to combine these four tinyints into a varbinary(4) -- I can only find C#/VB examples using paramterized SQL. This is fine and good, but I'm trying to create an SQL Function do use in an INSTEAD OF INSERT trigger.

share|improve this question
I am open to other/better ways to parse the IP as well, but I've found a few examples using PARSENAME for IPv4 and it seems to work well... – Nate Jan 26 '12 at 22:57
Possible duplicate of… – GSerg Jan 26 '12 at 23:01
up vote 2 down vote accepted
@stringIP = ''
    cast(CAST(PARSENAME(@stringIP, 4) as tinyint) as varbinary(1)) +
    cast(CAST(PARSENAME(@stringIP, 3) as tinyint) as varbinary(1)) +
    cast(CAST(PARSENAME(@stringIP, 2) as tinyint) as varbinary(1)) +
    cast(CAST(PARSENAME(@stringIP, 1) as tinyint) as varbinary(1))
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.