Remove Trailing Spaces and Update in Columns in SQL Server
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))
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))
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