Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 Trim all columns

Author  Topic 

squashjunkie
Starting Member

9 Posts

Posted - 2006-06-13 : 11:31:46
Hi,

I have several tables where I need to trim the trailing spaces in all columns. I could write a statement for each table & column such as
UPDATE <Table>
SET <Column1> = LTRIM(RTRIM(<Column1>)) etc etc
but would there be an easier way to do this?
I'm thinking there must be a way of setting the column name as a variable and looping through, but am a little stuck on how to start.

Can anyone give me any pointers?

TIA

Kristen
Test

22859 Posts

Posted - 2006-06-13 : 11:36:56
[code]
SELECT 'UPDATE [' + TABLE_SCHEMA + '].[' + TABLE_NAME + '] '
+ 'SET [' + COLUMN_NAME + '] = LTRIM(RTRIM([' + COLUMN_NAME + '])) '
+ 'WHERE [' + COLUMN_NAME + '] <> LTRIM(RTRIM([' + COLUMN_NAME + ']))'
+ CHAR(13) + CHAR(10) + 'GO'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE DATA_TYPE IN ('varchar', 'nvarchar')
ORDER BY TABLE_NAME, COLUMN_NAME
[/code]
will generate a script which you can hand-edit to chop out anything irrelevant

Kristen
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2006-06-14 : 03:12:09
Also, if you use front end application to send data, then trim the data there before sending into table

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

Maux Maux
Starting Member

10 Posts

Posted - 2006-06-14 : 12:27:35
Here is a loop version that is dirty and nasty.


USE YOURDATABASENAME

declare @Foo table (tablename sysname,colname sysname)

insert into @Foo
SELECT
OBJ.NAME as tablename
,COL.NAME AS colname
FROM
SYSOBJECTS OBJ
INNER JOIN
SYSCOLUMNS COL
ON
OBJ.ID = COL.ID
INNER JOIN
SYSTYPES TYP
ON
COL.XTYPE = TYP.XTYPE
WHERE

TYP.NAME <> 'sysname'
AND
OBJ.XTYPE = 'U'


declare @SQL varchar(1000)
declare @bar int
declare @tb sysname
declare @col sysname
select @Bar = count(*) from @Foo
while @Bar > 0

begin
select @tb = tablename from @Foo
select @col = colname from @Foo
SET @SQL = ''
SET @SQL = 'UPDATE ' + @tb + ' SET ' + @col + ' = LTRIM(RTRIM(['
+ @col + '])) WHERE ' + @col + ' <> LTRIM(RTRIM([' + @col + ']))'

select @SQL

SET @bar = @Bar-1
end


Ugly, dirty, filthy, but you dont have to chop anything out, just run it once.
Go to Top of Page
   

- Advertisement -