Take the 2-minute tour ×
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.

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 = '192.168.0.3'
select 
    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 stackoverflow.com/questions/695568/… –  GSerg Jan 26 '12 at 23:01
add comment

1 Answer 1

up vote 2 down vote accepted
@stringIP = '192.168.0.3'
select 
    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
add comment

Your Answer

 
discard

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.