Do you know if there\'s a quick way in sql server (via transact-sql) that I could trim all the database string fields.
loop over information_schema.columns and RTRIM the varchar/nvarchar columns by creating the update statement dynamically
Just make sure you are doing a trim on VARCHAR string fields, not CHAR fields :)
That wouldn't do much good.
Your question is a bit vague but is this what you are after?
UPDATE mytable SET mycolumn= LTRIM(RTRIM(mycolumn))
That will remove both leading and trailing spaces from all values in the 'mycolumn' column in the 'mytable' table.
OK, that was quick and dirty but i have been sufficiently motivated by a current project to do this 'properly' - and with no cursors either, but a little sql concatenation trick. Does use dynamic sql though:
--exec spGenerateTrimStatements 'StaticImportMaturities'
ALTER PROCEDURE spGenerateTrimStatements
(
@TableName NVARCHAR(100)
)
AS
DECLARE @Cr char(2),
@OutputString nvarchar(max)
SELECT @Cr = CHAR(13) + CHAR(10)
SET NOCOUNT ON
-- Create table to store commands
CREATE TABLE #tOutput(OutputText nvarchar(500), RowID int identity(1,1))
-- Build up commands
INSERT #tOutput(OutputText)
SELECT 'UPDATE ' + @TableName + ' SET '
INSERT #tOutput(OutputText)
SELECT '[' + Column_Name + '] = ' + 'LTRIM(RTRIM([' + Column_Name + '])), '
FROM INFORMATION_SCHEMA.Columns
WHERE Table_Name = @TableName
AND Data_Type LIKE '%CHAR%'
-- Trim last comma
UPDATE #tOutput
SET OutputText = LEFT(OutputText, LEN(OutputText)-1)
WHERE RowID = (SELECT Max(RowID) FROM #tOutput)
-- use subselect to concatenate the command string
SELECT @OutputString = ISNULL(@OutputString, '') + ISNULL(OutputText, '')
FROM (SELECT OutputText
FROM #tOutput) TextOutput
-- run the command
EXEC sp_ExecuteSQL @OutputString
Updated the answer of dan to use all tables in the database. Just run the snippet and copy the result to execute.
SELECT 'UPDATE [' + TABLE_SCHEMA + '].[' + TABLE_NAME + '] SET [' + Column_Name + '] = ' + 'LTRIM(RTRIM([' + Column_Name + ']))'
FROM INFORMATION_SCHEMA.Columns c
WHERE Data_Type LIKE '%CHAR%'
Thanks guys,
Entaroadun code worked pretty well for me, I just had to do some small changes to my requierements, and also I had to reset @colum_list on each iteration.
...
PRINT REPLACE(REPLACE(@template, '{@column_list}', @column_list),
'{@OBJECT_NAME}', @OBJECT_NAME)
PRINT 'GO'
SELECT @column_list = null
FETCH NEXT FROM c INTO @OBJECT_NAME
...