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
100% working
UPDATE table_name SET "column_name"=replace("column_name", ' ', ''); //Remove white space
UPDATE table_name SET "column_name"=replace("column_name", '\n', ''); //Remove newline
UPDATE table_name SET "column_name"=replace("column_name", '\t', ''); //Remove all tab
You can use "column_name"
or column_name
Thanks
Subroto
If there are multiple white spaces in a string, then replace may not work correctly. For that, the following function should be used.
CREATE FUNCTION RemoveAllSpaces
(
@InputStr varchar(8000)
)
RETURNS varchar(8000)
AS
BEGIN
declare @ResultStr varchar(8000)
set @ResultStr = @InputStr
while charindex(' ', @ResultStr) > 0
set @ResultStr = replace(@InputStr, ' ', '')
return @ResultStr
END
Example:
select dbo.RemoveAllSpaces('aa aaa aa aa a')
Output:
aaaaaaaaaa
Syntax for replacing a specific characters:
REPLACE ( string_expression , string_pattern , string_replacement )
For example in the string "HelloReplaceThingsGoing" Replace word is replaced by How
SELECT REPLACE('HelloReplaceThingsGoing','Replace','How');
GO
If it is an update on a table all you have to do is run this update multiple times until it is affecting 0 rows.
update tableName
set colName = REPLACE(LTRIM(RTRIM(colName)), ' ', ' ')
where colName like '% %'
if you want to remove spaces,-, and another text from string then use following :
suppose you have a mobile number in your Table like '718-378-4957' or ' 7183784957' and you want replace and get the mobile number then use following Text.
select replace(replace(replace(replace(MobileNo,'-',''),'(',''),')',''),' ','') from EmployeeContactNumber
Result :-- 7183784957
This does the trick of removing the spaces on the strings:
UPDATE
tablename
SET
columnname = replace(columnname, ' ', '');