Remove Trailing Spaces and Update in Columns in SQL Server
Asked Answered
C

15

178

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 those, and I want to have the data without any trailing spaces.

The company name is like "Amit Tech Corp "

I want the company name to be "Amit Tech Corp"

Crashing answered 8/2, 2013 at 21:59 Comment(0)
C
361

Try SELECT LTRIM(RTRIM('Amit Tech Corp '))

LTRIM - removes any leading spaces from left side of string

RTRIM - removes any spaces from right

In SQL Server 2017 or later:

TRIM - removes any spaces from left and right

Ex:

update table set CompanyName = LTRIM(RTRIM(CompanyName))
Catlin answered 8/2, 2013 at 22:0 Comment(3)
It should be noted that TRIM is now a supported method in SQL Server 2017+.Antony
I am using SQL Management Studio v17.8.1 and while I get Intellisense for the TRIM function, when I execute it, it says it is not valid. I had to use the code above. Weird.Octroi
@Octroi SQL Management Studio version is not version of SQL ServerDiphenyl
C
41

To just trim trailing spaces you should use

UPDATE
    TableName
SET
    ColumnName = RTRIM(ColumnName)

However, if you want to trim all leading and trailing spaces then use this

UPDATE
    TableName
SET
    ColumnName = LTRIM(RTRIM(ColumnName))
Carrissa answered 8/2, 2013 at 22:1 Comment(0)
P
20

SQL Server does not support for Trim() function.

But you can use LTRIM() to remove leading spaces and RTRIM() to remove trailing spaces.

can use it as LTRIM(RTRIM(ColumnName)) to remove both.

update tablename
set ColumnName= LTRIM(RTRIM(ColumnName))

Update : 2022

I had answered this question 7 years ago(in 2015). At that time there was not a direct function for trimming in SQL server.

But from SQL Server 2017, they introduced the Trim() function.

So anyone who uses SQL Server 2017 or a later version, can easily do the same thing as below.

update tablename
set ColumnName= TRIM(ColumnName)

However, if you use an older version, you will still have to use the way which I've mentioned 7 years ago.

Pelotas answered 14/12, 2015 at 5:43 Comment(0)
C
16

Well here is a nice script to TRIM all varchar columns on a table dynamically:

--Just change table name
declare @MyTable varchar(100)
set @MyTable = 'MyTable'

--temp table to get column names and a row id
select column_name, ROW_NUMBER() OVER(ORDER BY column_name) as id into #tempcols from INFORMATION_SCHEMA.COLUMNS 
WHERE   DATA_TYPE IN ('varchar', 'nvarchar') and TABLE_NAME = @MyTable

declare @tri int
select @tri = count(*) from #tempcols
declare @i int
select @i = 0
declare @trimmer nvarchar(max)
declare @comma varchar(1)
set @comma = ', '

--Build Update query
select @trimmer = 'UPDATE [dbo].[' + @MyTable + '] SET '

WHILE @i <= @tri 
BEGIN

    IF (@i = @tri)
        BEGIN
        set @comma = ''
        END
    SELECT  @trimmer = @trimmer + CHAR(10)+ '[' + COLUMN_NAME + '] = LTRIM(RTRIM([' + COLUMN_NAME + ']))'+@comma
    FROM    #tempcols
    where id = @i

    select @i = @i+1
END

--execute the entire query
EXEC sp_executesql @trimmer

drop table #tempcols
Cede answered 7/3, 2014 at 22:6 Comment(0)
G
7
update MyTable set CompanyName = rtrim(CompanyName)
Grooved answered 8/2, 2013 at 22:2 Comment(0)
P
3

Use the TRIM SQL function.

If you are using SQL Server try :

SELECT LTRIM(RTRIM(YourColumn)) FROM YourTable
Perlis answered 8/2, 2013 at 22:2 Comment(0)
W
3

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'

Whitefish answered 20/3, 2017 at 4:27 Comment(0)
R
2

I had the same problem after extracting data from excel file using ETL and finaly i found solution there :

https://www.codeproject.com/Tips/330787/LTRIM-RTRIM-doesn-t-always-work

hope it helps ;)

Ralleigh answered 13/5, 2017 at 10:20 Comment(0)
B
1

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;
Beyond answered 18/1, 2020 at 10:34 Comment(0)
W
0
SELECT TRIM(ColumnName) FROM dual;
Winou answered 7/12, 2014 at 4:37 Comment(1)
This is an Oracle query, OP is using Microsoft SQL ServerDecimalize
T
0

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))

Trager answered 16/4, 2015 at 19:48 Comment(2)
Trim is not available by default, it's a DAX feature: msdn.microsoft.com/en-us/library/gg413422.aspxDecimalize
TRIM() available from SQL2017 learn.microsoft.com/en-us/sql/t-sql/functions/trim-transact-sql (and has option to remove characters other than SPACE)Tai
K
0

Example:

SELECT TRIM('   Sample   ');

Result: 'Sample'

UPDATE TableName SET ColumnName = TRIM(ColumnName)
Korykorzybski answered 29/10, 2015 at 11:12 Comment(2)
SQL Server does not supported for Trim() function. But you can use LTRIM() and RTRIM(). If you want to use both together you can use LTRIM(RTRIM(ColumnName))Pelotas
This is an Oracle query, OP is using Microsoft SQL ServerDecimalize
A
0

To remove Enter:

Update [table_name] set
[column_name]=Replace(REPLACE([column_name],CHAR(13),''),CHAR(10),'')

To remove Tab:

Update [table_name] set
[column_name]=REPLACE([column_name],CHAR(9),'')
Anthropomorphous answered 1/10, 2018 at 4:31 Comment(0)
A
0

None of these will work if your datatype is Varchar. Make sure to change your datatype to Nvarchar.

Alithea answered 16/6, 2023 at 14:11 Comment(0)
S
0

TrimShort.sql

/* Summary: Trims the data of selected columns in a selected table
* Works for: SQL Server Management Studio v18.10 
* 
* How to use:
* ctrl + F, 
* click V on the left side of textbox
* copy a field's name from list below > paste in Search
* write your field's name > Replace in Search
* click Replace All
* repeat for all fields
*
* Fields to replace:
* MyDatabase - set to your database name
* MyTable - set to your table name
* Column1 - set to your table's column name
* Column2 - set to your table's column name
*/

USE [MyDatabase]
GO
UPDATE [dbo].[MyTable] SET
    [Column1] = TRIM([Column1])
    ,[Column2] = TRIM([Column2])
GO

TrimLong.sql - I wrote this first. It works like above version.

/* Summary:
* Trim the data of selected columns in a selected table
*
* Works for: SQL Server Management Studio v18.10 
* 
* How to use:
* ctrl + F, 
* click V on the left side of textbox
* copy a field's name from list below > paste in Search
* write your field's name > Replace in Search
* click Replace All
* repeat for all fields
*
* Fields to replace:
* MyDatabase - set to your database name
* MyTable - set to your table name
* MyColumnId - set to your table's column ID name
* Column1 - set to your table's column name
* Column2 - set to your table's column name
*/

USE [MyDatabase]
GO

--Number of rows in the table
DECLARE @RowCnt INT;
SET @RowCnt = (SELECT COUNT(*) FROM [dbo].[MyTable])

--Row ID for a loop
DECLARE @RowId INT;
SET @RowId = 1

--Print number of rows to Update
PRINT 'Number of rows:' + convert(varchar(4), @RowCnt)

--Loop for each row
WHILE @RowId <= @RowCnt
BEGIN
    --Print Row ID
    PRINT 'RowId:' + convert(varchar(4), @RowId)

    --Trim a row data for selected Columns
    UPDATE [dbo].[MyTable] SET
        [Column1] = (SELECT TRIM([Column1]) from [dbo].[MyTable] WHERE MyColumnId = @RowId)
        ,[Column2] = (SELECT TRIM([Column2]) from [dbo].[MyTable] WHERE MyColumnId = @RowId)
        WHERE MyColumnId = @RowId

    --Increase Row ID
    SET @RowId = @RowId + 1
END
GO

Example of use

When you were cleaver enough to make char(15) fields but then it turned out that you were reading a value with a whitespace tail, so you will change it to nvarchar(15).

Stockish answered 6/7, 2023 at 10:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.