ron_finnerty
asked on
SQL Code to parse out an address
Hello,
I am trying to figure out T-SQL code to parse out an address in MS SQL 2000. Using 123MainStreet as an example, I need to be able to add a space between '123' and 'MainStreet'. If there is a way to add a space between 'Main' and 'Street', that would be a big help as well. But at a minimum, adding the space between house number and street name would be a huge help.
I am trying to figure out T-SQL code to parse out an address in MS SQL 2000. Using 123MainStreet as an example, I need to be able to add a space between '123' and 'MainStreet'. If there is a way to add a space between 'Main' and 'Street', that would be a big help as well. But at a minimum, adding the space between house number and street name would be a huge help.
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
ASKER
Thanks cmhunty- unfortunately, the data coming in to me is a mix of some addresses having all caps, some all lower case, and some being a mix of caps/lower case. At this point, just being able to add a space between the house number and the street name is what I am looking for. I see your point with the 123A vs. 123, but that is something I will have to deal with at another time.
ASKER
Thanks bhess1- what if I just want to put a space between the last number in the house number and the first letter of the street address? Is that something that is a bit more simple to code?
You can just remove the REPLACE statements to do that. Also, you can replace part of the code, ending up with:
DECLARE FUNCTION dbo.ufn_ParseAddress (
@addr varchar(255)
)
RETURNS varchar(255)
AS
BEGIN
DECLARE @ptr int
DECLARE @ptr2 int
SET @ptr = 0
SET @Work = ''
WHILE @ptr < Len(@addr)
BEGIN
SET @ptr2 = @ptr
SET @ptr = @ptr + 1
IF Substring(@addr, @ptr, 1) LIKE '[abcdefghijklmnopqrstuvwx yzABCDEFGH IJKLMNOPQR STUVWXYZ]'
SET @ptr = 255 -- exit out
END
IF @ptr2 < Len(@addr) AND @ptr2 > 0
BEGIN
SET @addr = LEFT(@Addr, @ptr2) + ' ' + Substring(@addr, @ptr2+1, Len(@addr))
END
RETURN @addr
END
DECLARE FUNCTION dbo.ufn_ParseAddress (
@addr varchar(255)
)
RETURNS varchar(255)
AS
BEGIN
DECLARE @ptr int
DECLARE @ptr2 int
SET @ptr = 0
SET @Work = ''
WHILE @ptr < Len(@addr)
BEGIN
SET @ptr2 = @ptr
SET @ptr = @ptr + 1
IF Substring(@addr, @ptr, 1) LIKE '[abcdefghijklmnopqrstuvwx
SET @ptr = 255 -- exit out
END
IF @ptr2 < Len(@addr) AND @ptr2 > 0
BEGIN
SET @addr = LEFT(@Addr, @ptr2) + ' ' + Substring(@addr, @ptr2+1, Len(@addr))
END
RETURN @addr
END
Oops - remove the SET @Work line
ASKER
Bhess1- that did the trick- thanks
First thing you really need to do is specify EXACTLY what rules you want and go through them one by one.
Your example above - iterate thought the characters and move the characters to another string one by one putting a space before each capital. This would possibly not work as you'd require it for my example