TSQL 2008 Using LTrim(RTrim and still have spaces in the data

末鹿安然 提交于 2019-12-03 18:03:46

问题


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  

回答1:


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]



回答2:


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), '')))



回答3:


Use:

WHEN PropStreetAddr is NOT NULL THEN
   (SELECT LTRIM(RTRIM((REPLACE(PropStreetAddr, 
                                SUBSTRING(PropStreetAddr, 
                                          PATINDEX('%[^a-zA-Z0-9 '''''']%', PropStreetAddr), 1), '') AS PropStreetAddr)



回答4:


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



来源:https://stackoverflow.com/questions/3374888/tsql-2008-using-ltrimrtrim-and-still-have-spaces-in-the-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!