What is the best way to remove all spaces from a string in SQL Server 2008?
LTRIM(RTRIM(\' a b \'))
would remove all spaces at the right and left of th
I would use a REPLACE
select REPLACE (' Hello , How Are You ?', ' ', '' )
REPLACE
Just a tip, in case you are having trouble with the replace function, you might have the datatype set to nchar (in which case it is a fixed length and it will not work).
To make all of the answers above complete, there are additional posts on StackOverflow on how to deal with ALL whitespace characters (see https://en.wikipedia.org/wiki/Whitespace_character for a full list of these characters):
Simply replace it;
SELECT REPLACE(fld_or_variable, ' ', '')
Edit:
Just to clarify; its a global replace, there is no need to trim()
or worry about multiple spaces for either char
or varchar
:
create table #t (
c char(8),
v varchar(8))
insert #t (c, v) values
('a a' , 'a a' ),
('a a ' , 'a a ' ),
(' a a' , ' a a' ),
(' a a ', ' a a ')
select
'"' + c + '"' [IN], '"' + replace(c, ' ', '') + '"' [OUT]
from #t
union all select
'"' + v + '"', '"' + replace(v, ' ', '') + '"'
from #t
Result
IN OUT
===================
"a a " "aa"
"a a " "aa"
" a a " "aa"
" a a " "aa"
"a a" "aa"
"a a " "aa"
" a a" "aa"
" a a " "aa"
Check and Try the below script (Unit Tested)-
--Declaring
DECLARE @Tbl TABLE(col_1 VARCHAR(100));
--Test Samples
INSERT INTO @Tbl (col_1)
VALUES
(' EY y
Salem')
, (' EY P ort Chennai ')
, (' EY Old Park ')
, (' EY ')
, (' EY ')
,(''),(null),('d
f');
SELECT col_1 AS INPUT,
LTRIM(RTRIM(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(col_1,CHAR(10),' ')
,CHAR(11),' ')
,CHAR(12),' ')
,CHAR(13),' ')
,CHAR(14),' ')
,CHAR(160),' ')
,CHAR(13)+CHAR(10),' ')
,CHAR(9),' ')
,' ',CHAR(17)+CHAR(18))
,CHAR(18)+CHAR(17),'')
,CHAR(17)+CHAR(18),' ')
)) AS [OUTPUT]
FROM @Tbl;
this is useful for me:
CREATE FUNCTION dbo.TRIM(@String VARCHAR(MAX))
RETURNS VARCHAR(MAX)
BEGIN
RETURN LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@String,CHAR(10),'[]'),CHAR(13),'[]'),char(9),'[]'),CHAR(32),'[]'),'][',''),'[]',CHAR(32))));
END
GO
.