views:

26

answers:

3

I am a bit of an sql noob so please forgive. I can't seem to find a usage example of LTRIM anywhere.

I have a NVARCHAR column in my table in which a number of entries have leading whitespace - I'm presuming if I run this it should do the trick:

SELECT LTRIM( ColumnName)
  From TableName;

Will this give the desired result?

+3  A: 

No, it will trim leading spaces but not all white space (e.g. carriage returns).

Edit It seems you are looking for an UPDATE query that will remove leading and trailing whitespace.

If by that you only mean "normal" spaces just use

    UPDATE TableName
   SET ColumnName = LTRIM(RTRIM(ColumnName ))

For all white space this should do it (from the comments here). Backup your data first!

    UPDATE TableName
   SET ColumnName = 
     SUBSTRING(
    ColumnName,
    PATINDEX('%[^ ' + char(09) + char(10) + char(13)  + char(20)  + ']%', 
    ColumnName),
    LEN(ColumnName) - PATINDEX('%[^ ' + char(09) + char(10) + char(13)  + char(20)  + ']%'
   , ColumnName) - 
    PATINDEX('%[^ ' + char(09) + char(10) + char(13)  + char(20)  + ']%', 
     REVERSE(ColumnName)) + 2) 
Martin Smith
+1  A: 

Did you run it to find out? It's just a select, it won't blow up your database. But, yes.

Select LTRIM(myColumn) myColumn
From   myTable

Should return the myColumn values with any leading whitespace removed. Note this is only leading whitespace.

EDIT To Update the column, with the above, you'd do:

Update myTable
Set myColumn = LTRIM(myColumn)
From myTable
AllenG
I take it I would do an RTrim to clean up the right side too.
Chin
@Chin - yes. I believe there is also a TRIM() function (but its been too long since I've looked, so I'm not 100% sure) which would trim both leading and trailing spaces. And the other gentlemen are correct, it won't remove carriage returns.
AllenG
@AllenG: TSQL doesn't have a TRIM() - just RTRIM and LTRIM. You want TRIM, got to use UDF or CLR...
OMG Ponies
@OMG Ponies: Okay, I remember now. We always used LTRIM(RTRIM(column)). Like I said, been too long since I've used the functions at all...
AllenG
+2  A: 

Your example will work to remove the leading spaces. This will only select it from the database. IF you need to actually change the data in your table, you will need to write an UPDATE statement something like:

UPDATE TableName
SET ColumnName = LTRIM(ColumnName)

If you need to remove spaces from the right side, you can use RTRIM.

Here is a list of the string functions in SQL Server 2005 that I always refer to: http://msdn.microsoft.com/en-us/library/ms181984(v=SQL.90).aspx

Lance Fisher
Thanks, that link will come in handy.
Chin