Link to home
Start Free TrialLog in
Avatar of rmm2001
rmm2001Flag for United States of America

asked on

tsql clean non printable chars using xml path

Hi guys -

I have a bunch of tables that have non printable characters in them and I need to get them out. Here's what I have so far...which works great to clean the bad stuff. Until I run it and get the original name as a name with a bunch of non printables (I'd paste but it wont' show up) and then the cleaned name as "Johnson & Company" instead of "Johnson & Company                       " like it did in the first place.

My select statement at the bottom is to select only the records which have the bad chars. (I'll use that to update my tables.)

Any clues as to what I'm doing wrong/not doing where I'm getting this? (Doing it both for SQL2005 and 2008)

Thanks!
;WITH Num1 (n) AS (SELECT 1 UNION ALL SELECT 1),
Num2 (n) AS (SELECT 1 FROM Num1 AS X, Num1 AS Y),
Num3 (n) AS (SELECT 1 FROM Num2 AS X, Num2 AS Y),
Num4 (n) AS (SELECT 1 FROM Num3 AS X, Num3 AS Y),
Nums (n) AS (SELECT ROW_NUMBER() OVER(ORDER BY n) FROM Num4),

CleanCTE
AS
(SELECT CompanyID, CompanyName,
       CAST ((SELECT CASE WHEN ASCII(SUBSTRING(CompanyName, n, 1))
                         BETWEEN 0x00 AND 0x1F 
                         OR ASCII(SUBSTRING(CompanyName, n, 1)) BETWEEN 0x80 AND 0xBF
                    THEN ''
                    ELSE SUBSTRING(CompanyName, n, 1)
               END + ''
        FROM Company AS B
        JOIN Nums
          ON n <= LEN(CompanyName)
        WHERE B.CompanyID = A.CompanyID
        Order by Nums.N
        FOR XML PATH(''), TYPE) AS VARCHAR(256)) AS CleanName
 FROM Company AS A)

SELECT TOP 100 o.CompanyName, CleanName
FROM
	CleanCTE cte
JOIN
	Company o on o.CompanyID = cte.CompanyID
WHERE
	LEN(CleanName) <> LEN(o.OperatorName)

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of cyberkiwi
cyberkiwi
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of rmm2001

ASKER

That works! Thank you! I didn't know about the spt_values table