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.
| 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 etcbut 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.COLUMNSWHERE 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 irrelevantKristen |
 |
|
|
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 tableMadhivananFailing to plan is Planning to fail |
 |
|
|
Maux Maux
Starting Member
10 Posts |
Posted - 2006-06-14 : 12:27:35
|
Here is a loop version that is dirty and nasty.USE YOURDATABASENAMEdeclare @Foo table (tablename sysname,colname sysname)insert into @FooSELECT OBJ.NAME as tablename ,COL.NAME AS colname FROM SYSOBJECTS OBJ INNER JOIN SYSCOLUMNS COL ON OBJ.ID = COL.IDINNER JOIN SYSTYPES TYP ON COL.XTYPE = TYP.XTYPEWHERE TYP.NAME <> 'sysname' AND OBJ.XTYPE = 'U'declare @SQL varchar(1000)declare @bar intdeclare @tb sysnamedeclare @col sysnameselect @Bar = count(*) from @Foowhile @Bar > 0beginselect @tb = tablename from @Fooselect @col = colname from @FooSET @SQL = ''SET @SQL = 'UPDATE ' + @tb + ' SET ' + @col + ' = LTRIM(RTRIM([' + @col + '])) WHERE ' + @col + ' <> LTRIM(RTRIM([' + @col + ']))' select @SQLSET @bar = @Bar-1end Ugly, dirty, filthy, but you dont have to chop anything out, just run it once. |
 |
|
|
|
|
|
|
|