Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase 1234»»»

Remove non printable characters Expand / Collapse
Author
Message
Posted Friday, February 5, 2010 4:22 AM
SSC-Enthusiastic

SSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-Enthusiastic

Group: General Forum Members
Last Login: Monday, May 5, 2014 8:24 AM
Points: 133, Visits: 617
Hi,
Is there an equivilent function to Excel's 'CLEAN' in SQL to remove non printable characters?.

Thanks,
G
Post #860321
Posted Friday, February 5, 2010 4:46 AM
SSCrazy

SSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazy

Group: General Forum Members
Last Login: Monday, October 21, 2013 12:32 AM
Points: 2,556, Visits: 2,593
I don't think so there is any equivalent function in SQL Server. But you can create you own function using the existing REPLACE function.

--Ramesh

Post #860333
Posted Friday, February 5, 2010 4:54 AM
SSC-Enthusiastic

SSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-Enthusiastic

Group: General Forum Members
Last Login: Monday, May 5, 2014 8:24 AM
Points: 133, Visits: 617
That could work ... thanks for the suggestion!
Post #860338
Posted Friday, February 5, 2010 9:31 PM


SSC-Dedicated

SSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-Dedicated

Group: General Forum Members
Last Login: Yesterday @ 9:58 AM
Points: 36,995, Visits: 31,517
Ramesh Saive (2/5/2010)
I don't think so there is any equivalent function in SQL Server. But you can create you own function using the existing REPLACE function.


Heh.. Let's see some code. I believe you'll find it's a wee bit more difficult to do than just using REPLACE.


--Jeff Moden
"RBAR is pronounced "ree-bar" and is a "Modenism" for "Row-By-Agonizing-Row".

First step towards the paradigm shift of writing Set Based code:
Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column."

(play on words) "Just because you CAN do something in T-SQL, doesn't mean you SHOULDN'T." --22 Aug 2013

Helpful Links:
How to post code problems
How to post performance problems
Post #860998
Posted Friday, February 5, 2010 9:32 PM


SSC-Dedicated

SSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-Dedicated

Group: General Forum Members
Last Login: Yesterday @ 9:58 AM
Points: 36,995, Visits: 31,517
Grinja (2/5/2010)
That could work ... thanks for the suggestion!


Which unprintable characters? Just any character less than CHAR(32)???


--Jeff Moden
"RBAR is pronounced "ree-bar" and is a "Modenism" for "Row-By-Agonizing-Row".

First step towards the paradigm shift of writing Set Based code:
Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column."

(play on words) "Just because you CAN do something in T-SQL, doesn't mean you SHOULDN'T." --22 Aug 2013

Helpful Links:
How to post code problems
How to post performance problems
Post #860999
Posted Saturday, February 6, 2010 1:20 AM
SSCrazy

SSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazy

Group: General Forum Members
Last Login: Monday, October 21, 2013 12:32 AM
Points: 2,556, Visits: 2,593
Jeff Moden (2/5/2010)
Ramesh Saive (2/5/2010)
I don't think so there is any equivalent function in SQL Server. But you can create you own function using the existing REPLACE function.


Heh.. Let's see some code. I believe you'll find it's a wee bit more difficult to do than just using REPLACE.


Ah..., Here is the code

DECLARE @Characters TABLE( SomeChar CHAR(1) NOT NULL )
DECLARE @SomeText VARCHAR(100)

SELECT @SomeText = 'Ticking away the moments that make up a dull day, Fritter and waste the hours in an offhand way.'

INSERT @Characters( SomeChar )
SELECT 't' UNION ALL
SELECT 'i' UNION ALL
SELECT 'c'

SELECT @SomeText = REPLACE( @SomeText, SomeChar, '' )
FROM @Characters

PRINT @SomeText



--Ramesh

Post #861028
Posted Saturday, February 6, 2010 11:47 AM


SSC-Dedicated

SSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-Dedicated

Group: General Forum Members
Last Login: Yesterday @ 9:58 AM
Points: 36,995, Visits: 31,517
My apologies, Ramesh. I should have qualified my statement. Instead of saying...

"I believe you'll find it's a wee bit more difficult to do than just using REPLACE."

... I should have said...

"I believe you'll find it's a wee bit more difficult to do it in a high performance manner using just REPLACE."

Let's see what I mean. First, we need two test tables... "#Dirty" will contain some characters that we need to remove and "#Clean" will have no characters to be removed.

--==============================================================================
-- Setup the test tables
--==============================================================================
--===== Conditionally remove the test tables so we can easily retest
IF OBJECT_ID('TempDB..#Dirty','U') IS NOT NULL
DROP TABLE #Dirty;

IF OBJECT_ID('TempDB..#Clean','U') IS NOT NULL
DROP TABLE #Clean;
GO
--===== Build the "dirty" table where each row has
-- at least 4 characters to remove
SELECT TOP 100000
CAST(NEWID() AS VARCHAR(100)) AS SomeText
INTO #Dirty
FROM Master.sys.All_Columns ac1,
Master.sys.All_Columns ac2;

--===== Build the "clean" table where each row has
-- NO characters to remove
SELECT TOP 100000
REPLICATE('B',26) AS SomeText
INTO #Clean
FROM Master.sys.All_Columns ac1,
Master.sys.All_Columns ac2;
GO

Now, let's put your code into a function and some slightly different code. Please... no one faint and no one write to their Congressman... I'm going to use a WHILE loop for this one because my tests show that this is one of the few places where a WHILE loop will beat a Tally table.

--==============================================================================
-- Setup the functions to test
--==============================================================================
--===== Do these tests in a nice safe place that everyone has.
USE TempDB;
GO
--===== Build a function using "Replace"
CREATE FUNCTION dbo.CleanWithReplace
(@SomeText VARCHAR(100))
RETURNS VARCHAR(100)
AS
BEGIN
DECLARE @Characters TABLE(SomeChar CHAR(1) NOT NULL)
INSERT @Characters( SomeChar )
SELECT 'A' UNION ALL
SELECT 'E' UNION ALL
SELECT '-'

SELECT @SomeText = REPLACE( @SomeText, SomeChar, '' )
FROM @Characters

RETURN @SomeText
END;
GO
--===== Build a function using "Stuff"
CREATE FUNCTION dbo.RemoveNonPrintable
-- Modified by Jeff Moden
(@String VARCHAR(8000))
RETURNS VARCHAR(8000) AS
BEGIN
DECLARE @IncorrectCharLoc SMALLINT,
@Pattern CHAR(7)

SELECT @Pattern = '%[-AE]%',
@IncorrectCharLoc = PATINDEX(@Pattern, @String)

WHILE @IncorrectCharLoc > 0
SELECT @string = STUFF(@String, @IncorrectCharLoc, 1, ''),
@IncorrectCharLoc = PATINDEX(@Pattern, @String)
RETURN @string
END
GO


Now, we'll run some tests. Each function will be executed against the "dirty" table and the "clean" table while measuring performance using Profiler. Please, read the comments in the code... they explain how the test was done.

--==============================================================================
-- Now we'll do the tests. I have Profiler measuring SQL:Batch Completed
-- against the SPID that I'm running these tests from. Also notice that
-- I've taken the time to take the display the results out of the picture
-- by returning the result to a "throw away" variable (@BitBucket).
--==============================================================================
GO
--===== CleanWithStuff against "dirty"
DECLARE @BitBucket VARCHAR(8000);
SELECT @BitBucket = dbo.CleanWithStuff(SomeText)
FROM #Dirty;
GO
--===== CleanWithReplace against "dirty"
DECLARE @BitBucket VARCHAR(8000);
SELECT @BitBucket = dbo.CleanWithReplace(SomeText)
FROM #Dirty;
GO
--===== CleanWithStuff against "clean"
DECLARE @BitBucket VARCHAR(8000);
SELECT @BitBucket = dbo.CleanWithStuff(SomeText)
FROM #Clean;
GO
--===== CleanWithReplace against "clean"
DECLARE @BitBucket VARCHAR(8000);
SELECT @BitBucket = dbo.CleanWithReplace(SomeText)
FROM #Clean;
GO


Here's the output from the Profiler trace...


As you can see, the STUFF method is a whole lot faster even on just a paltry 100,000 rows. As another benefit, the REPLACE method takes about the same amount of time to wade through the rows whether there's anything to clean out or not. The STUFF method runs a lot faster because it will short-circuit out of the function if there's nothing to do.

And, that's just to check for 3 characters that we want to remove. There are 33 non-printable characters just in the basic ASCII character set. Those characters are CHAR(0) through CHAR(31) and CHAR(127).

Heh... I know what's coming next. A lot of people would justify using the REPLACE code by saying it will only be used on one variable at a time from a GUI and the performance is probably good enough for even 10,000 simultaneous "hits". Those people would be absolutely correct.

What those people don't understand is that it's a function, i.e. easily "Reusable Code", and there's nothing in the code to control who uses it or why. So, some developer given an assignment to create an ETL package that will handle hundreds of million row files a day runs across the "Reusable Code" and uses it. Considering that the REPLACE function takes 30 seconds (on my humble desktop) to handle only 100,000 rows, it'll take a good 5 minutes to handle just one million row file and it's hammering the CPU the whole time. I'm thinking that would cause a major problem in the not-so-unusual scenario I just gave.

That's what I originally meant by it not being so easy to do with REPLACE.


--Jeff Moden
"RBAR is pronounced "ree-bar" and is a "Modenism" for "Row-By-Agonizing-Row".

First step towards the paradigm shift of writing Set Based code:
Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column."

(play on words) "Just because you CAN do something in T-SQL, doesn't mean you SHOULDN'T." --22 Aug 2013

Helpful Links:
How to post code problems
How to post performance problems


  Post Attachments 
TraceOutputFromTest.gif (2,049 views, 5.17 KB)
Post #861140
Posted Saturday, February 6, 2010 12:15 PM


SSC-Dedicated

SSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-Dedicated

Group: General Forum Members
Last Login: Yesterday @ 9:58 AM
Points: 36,995, Visits: 31,517
Grinja (2/5/2010)
Hi,
Is there an equivilent function to Excel's 'CLEAN' in SQL to remove non printable characters?.

Thanks,
G


I believe this will do it for you...

 CREATE FUNCTION dbo.RemoveNonDisplayChars
/********************************************************************
Purpose:
Remove the non-displayable control characters from CHAR(0) to
CHAR(31) and the DELETE character CHAR(127).

Revision History:
Rev 00 - Jeff Moden - 06 Feb 2010 - Initial Release and Unit Test
********************************************************************/
--===== Declare the I/O parameters
(@pString VARCHAR(8000))
RETURNS VARCHAR(8000)
AS
BEGIN

--===== Declare Local variables
DECLARE @IncorrectCharLoc SMALLINT, --Position of bad character
@Pattern CHAR(37) --Bad characters to look for

SELECT @Pattern = '%['
+ CHAR(0)+CHAR(1)+CHAR(2)+CHAR(3)+CHAR(4)
+ CHAR(5)+CHAR(6)+CHAR(7)+CHAR(8)+CHAR(9)
+ CHAR(10)+CHAR(11)+CHAR(12)+CHAR(13)+CHAR(14)
+ CHAR(15)+CHAR(16)+CHAR(17)+CHAR(18)+CHAR(19)
+ CHAR(20)+CHAR(21)+CHAR(22)+CHAR(23)+CHAR(24)
+ CHAR(25)+CHAR(26)+CHAR(27)+CHAR(28)+CHAR(29)
+ CHAR(30)+CHAR(31)+CHAR(127)
+ ']%',
@IncorrectCharLoc = PATINDEX(@Pattern, @pString)

WHILE @IncorrectCharLoc > 0
SELECT @pString = STUFF(@pString, @IncorrectCharLoc, 1, ''),
@IncorrectCharLoc = PATINDEX(@Pattern, @pString)
RETURN @pString
END
GO




--Jeff Moden
"RBAR is pronounced "ree-bar" and is a "Modenism" for "Row-By-Agonizing-Row".

First step towards the paradigm shift of writing Set Based code:
Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column."

(play on words) "Just because you CAN do something in T-SQL, doesn't mean you SHOULDN'T." --22 Aug 2013

Helpful Links:
How to post code problems
How to post performance problems
Post #861154
Posted Monday, February 8, 2010 1:22 AM
SSCrazy

SSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazy

Group: General Forum Members
Last Login: Monday, October 21, 2013 12:32 AM
Points: 2,556, Visits: 2,593
Jeff Moden (2/6/2010)
...... I should have qualified my statement. Instead of saying...

"I believe you'll find it's a wee bit more difficult to do than just using REPLACE."

... I should have said...

"I believe you'll find it's a wee bit more difficult to do it in a high performance manner using just REPLACE.".......


I knew it was coming, Jeff. I know you would always come up with more optimized solution than this.

And I agree with you on the reusable optimized code; there is really no harm in using optimized code though it is for a one time or one row execution.

Thank you Jeff, for taking time and letting me know few of the cases where a while loop beats a tally table.

I wonder how many more cases I would see where a while loop beats a tally table.


--Ramesh

Post #861468
Posted Friday, February 26, 2010 9:40 PM


SSChampion

SSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampion

Group: General Forum Members
Last Login: 2 days ago @ 4:20 PM
Points: 11,194, Visits: 11,142
Hey Jeff,

Scalar T-SQL functions?! WHILE loops? I am genuinely shocked!

The REPLACE solution can be made to run an order of magnitude faster if we use an in-line table-valued function instead of an evil scalar function:

Create the in-line table-valued function
CREATE  FUNCTION dbo.IF_CleanWithReplace
(
@SomeText VARCHAR(100)
)
RETURNS TABLE
WITH SCHEMABINDING
AS RETURN
SELECT cleaned =
REPLACE(
REPLACE(
REPLACE(
@SomeText COLLATE SQL_LATIN1_GENERAL_CP1_CI_AS,
'A', SPACE(0)),
'E', SPACE(0)),
'-', SPACE(0));

Run the test
DECLARE @BitBucket VARCHAR(8000);
SELECT @BitBucket = iTVF.cleaned
FROM #Dirty D
CROSS
APPLY dbo.IF_CleanWithReplace(D.SomeText) iTVF;

Execution times (scalar function times in parentheses):

#Dirty: 501ms (13,234ms)

Paul

edit: code updated in-place to reflect Carl's excellent observation that the previous implementation was fast, but failed to return the correct results




Paul White
SQL Server MVP
SQLblog.com
@SQL_Kiwi
Post #873842
« Prev Topic | Next Topic »

Add to briefcase 1234»»»

Permissions Expand / Collapse