I have trailing spaces in a column in a SQL Server table called Company Name
.
All data in this column has trailing spaces.
I want to remove all
Try
SELECT LTRIM(RTRIM('Amit Tech Corp '))
LTRIM - removes any leading spaces from left side of string
RTRIM - removes any spaces from right
Ex:
update table set CompanyName = LTRIM(RTRIM(CompanyName))
Example:
SELECT TRIM(' Sample ');
Result: 'Sample'
UPDATE TableName SET ColumnName = TRIM(ColumnName)
SELECT TRIM(ColumnName) FROM dual;
If we also want to handle white spaces and unwanted tabs-
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;
If you are using SQL Server (starting with vNext) or Azure SQL Database then you can use the below query.
SELECT TRIM(ColumnName) from TableName;
For other SQL SERVER Database you can use the below query.
SELECT LTRIM(RTRIM(ColumnName)) from TableName
LTRIM - Removes spaces from the left
example: select LTRIM(' test ') as trim
= 'test '
RTRIM - Removes spaces from the right
example: select RTRIM(' test ') as trim
= ' test'
Well, it depends on which version of SQL Server you are using.
In SQL Server 2008 r2, 2012 And 2014 you can simply use TRIM(CompanyName)
SQL Server TRIM Function
In other versions you have to use set CompanyName = LTRIM(RTRIM(CompanyName))