question

NetDevGuy avatar image
NetDevGuy asked

Help to remove some spaces from file names in one column

Hi All, I am using MS SQL 2005 and I have a table called ipAssets in which there is a column called **fileName** (varchar(30)). This column value is used to build path statements which we then use to access the file whose name is in this column. Some of the values for the file names in this column contain one or more spaces before the file name itself which causes the path to be invalid and things break down from there. e.g. ' myFile.jpg' which causes the path **.../someplace/somefolder/ myFile.jpg** which is a bad path. I would like to find out how many records in ipAssets have been affected by this, and I also want to know how to safely remove the extra spaces from those records. I have researched this and found some trim functions that appear to sound right for the job (LTRIM and RTRIM) but I am not sure if using these is the correct approach, or if there is a better (safer) way to do both items above. Any help would be greatly appreciated. THANKS!
space
10 |1200 characters needed characters left characters exceeded

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

· Write an Answer
ThomasRushton avatar image
ThomasRushton answered
As you've found, using LTRIM(RTRIM(columname)) will do the job quite nicely. To find out how many records are affected: SELECT COUNT(*) FROM ipAssets WHERE fileName LTRIM(RTRIM(fileName)) What you might want to do is clean your data by: UPDATE ipAssets SET fileName = LTRIM(RTRIM(fileName)) WHERE fileName LTRIM(RTRIM(fileName))
2 comments
10 |1200 characters needed characters left characters exceeded

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

@ThomasRushton +1 but I would like to point out that rtrim is correct in the set part, but is not in the predicate. This is because presence of the trailing spaces does not affect string comparoson results. This is because the algorithm to compare 2 strings is ANSI compliant: the shorter of the 2 strings is right-padded with spaces until both have equal length and then the strings are compared (usually from left to right). In other words:
if 'hello' = 'hello  '
    select 'they are equal';
The above accidentally means that the update will fail to include any records where there are trailing spaces but there are no leading spaces. One way to make the update work properly is to apply the datalength to both parts in the predicate:
update ipAssets
SET fileName = LTRIM(RTRIM(fileName))
WHERE datalength(fileName)  datalength(LTRIM(RTRIM(fileName)));
4 Likes 4 ·
@Oleg - thanks for the tip! I keep learning here...
0 Likes 0 ·

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.