views:

52

answers:

2

I have data I cleaning up in an old data table prior to moving it to a new one. One of the fields has spaces in the column, right & left. I wrote the following code to address this and still have leading spaces?? The bulk of the data is clean when using this code but for some reason there are spaces prior to RT addresses... Has anyone else had this type of issue?

,CASE   
WHEN PropStreetAddr IS NOT NULL
 THEN  (CONVERT(VARCHAR(28),PropStreetAddr))  
WHEN PropStreetAddr is NOT NULL Then  (Select LTrim(RTrim(PropStreetAddr)) As PropStreetAddr)
     ELSE NULL END  as 'PROPERTY_STREET_ADDRESS'

Sample output data:

1234 20th St 
  RT 1 BOX 2  
560 King St  
610 Nowland Rd  
  RT 1  
1085 YouAreHere Ln  
  RT 24 Box 12  
+2  A: 

Use:

WHEN PropStreetAddr is NOT NULL THEN
   (SELECT LTRIM(RTRIM((REPLACE(PropStreetAddr, 
                                SUBSTRING(PropStreetAddr, 
                                          PATINDEX('%[^a-zA-Z0-9 '''''']%', PropStreetAddr), 1), '') AS PropStreetAddr)
OMG Ponies
Still no change, I am stumped.
JMS49
OMG Ponies
Yes I used the code as you wrote it. Put the data in WORD and asked it to show all hidden characters..sample data: ..124.. WOODLEY PARK RD ..1085...TRAIL CT ..765...K ST ..506..AVE B .1500..R..ST ..760...N STREET .1865..D ST .1810...A..STREET ..645...15TH..ST .....RT..1. This leads me to think that the trim combo is not working, but why?
JMS49
@JMS49: LTRIM/RTRIM only works on spaces at the respective edge - this will change two spaces into one: `REPLACE(PropStreetAddr, ' ', ' ')` Stupid comment eats spaces - should be two in the first, one in the second.
OMG Ponies
JMS49
@JMS49: Post a new question, link back to this one.
OMG Ponies
+2  A: 

Here's the expression that will work. I'm assuming there is no non-visible content. You should still pursue @OMG Ponies recommendation if you suspect it. And I think the PATINDEX expression can be added to this expression if you must deal with the non-visible content.

SQL Server CASE processes only one WHEN clause then breaks. So you are never getting to the second data conversion. Also, all NULL values will convert to NULL when you use the LTRIM and RTRIM functions. So, you don't need to test for it, unless you want to do something with the NULLs.

So, try this:

CONVERT(VARCHAR(28), LTRIM(RTRIM(PropStreetAddr))) as [PROPERTY_STREET_ADDRESS]
bobs
Bobs and @OMG Ponies you are the greatest it works! Terrific, I think my headache will now go away too! Thank you both. There are some wonderful folks on this site.
JMS49