A functional version (udf) that removes spaces, cr, lf, tabs or configurable.
select Common.ufn_RemoveWhitespace(' 234 asdf wefwef 3 x ', default) as S
Result: '234asdfwefwef3x'
alter function Common.RemoveWhitespace
(
@pString nvarchar(max),
@pWhitespaceCharsOpt nvarchar(max) = null -- default: tab, lf, cr, space
)
returns nvarchar(max) as
/*--------------------------------------------------------------------------------------------------
Purpose: Compress whitespace
Example: select Common.ufn_RemoveWhitespace(' 234 asdf wefwef 3 x ', default) as s
-- Result: 234asdfwefwef3x
Modified By Description
---------- ----------- --------------------------------------------------------------------
2018.07.24 crokusek Initial Version
--------------------------------------------------------------------------------------------------*/
begin
declare
@maxLen bigint = 1073741823, -- (2^31 - 1) / 2 (https://stackoverflow.com/a/4270085/538763)
@whitespaceChars nvarchar(30) = coalesce(
@pWhitespaceCharsOpt,
char(9) + char(10) + char(13) + char(32)); -- tab, lf, cr, space
declare
@whitespacePattern nvarchar(30) = '%[' + @whitespaceChars + ']%',
@nonWhitespacePattern nvarchar(30) = '%[^' + @whitespaceChars + ']%',
@previousString nvarchar(max) = '';
while (@pString != @previousString)
begin
set @previousString = @pString;
declare
@whiteIndex int = patindex(@whitespacePattern, @pString);
if (@whiteIndex > 0)
begin
declare
@whitespaceLength int = nullif(patindex(@nonWhitespacePattern, substring(@pString, @whiteIndex, @maxLen)), 0) - 1;
set @pString =
substring(@pString, 1, @whiteIndex - 1) +
iif(@whiteSpaceLength > 0, substring(@pString, @whiteIndex + @whiteSpaceLength, @maxLen), '');
end
end
return @pString;
end
go