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
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]
I've had the same problem - wrapping the string in a CAST(x as varbinary(64)) shows the hex and from this I see A000 - which I believe is non-breaking space.
To remove, try this (for UNICODE);
LTRIM(RTRIM(REPLACE(my-column, NCHAR(0x00A0), '')))
Use:
WHEN PropStreetAddr is NOT NULL THEN
(SELECT LTRIM(RTRIM((REPLACE(PropStreetAddr,
SUBSTRING(PropStreetAddr,
PATINDEX('%[^a-zA-Z0-9 '''''']%', PropStreetAddr), 1), '') AS PropStreetAddr)
I have a similar situation, initially I thought the LTRIM & RTRIM functions were not working correctly. However once I tested it out and could see that it was not a proper white space character (the actual character may be different to your offending non printable character), using:
ASCII
I found the character to be named 160, so then I did a replace like:
SELECT REPLACE('NaughtyString', CHAR(160),'')
Hope it helps somebody