tags:

views:

7635

answers:

3

For Example; SELECT TRIM(Names) FROM Customer

+16  A: 
SELECT LTRIM(RTRIM(Names)) AS Names FROM Customer
Ben Hoffstein
this is the easiest way to do it, just remember to alias your column being returned
Miles
@Miles - I added the alias for completeness.
Ben Hoffstein
+17  A: 

To Trim on the right, use:

SELECT RTRIM(Names) FROM Customer

To Trim on the left, use:

SELECT LTRIM(Names) FROM Customer

To Trim on the both sides, use:

SELECT LTRIM(RTRIM(Names)) FROM Customer
Kibbee
Incidentally, what possible reason could Microsoft have for including an LTRIM and RTRIM function without a TRIM? It's peculiar.
Ben Hoffstein
Because it is redundant. You can accomplish the same thing with LTRIM(RTRIM(var)).
Kibbee
Yes, but that's two function calls. You could say they are all redundant since TSQL has CHARINDEX and SUBSTRING, but that's an idiotic way to look at it.
Ben Hoffstein
A: 

I assume this is a one-off data scrubbing exercise. Once done, ensure you add database constraints to prevent bad data in the future e.g.

ALTER TABLE Customer ADD
   CONSTRAINT customer_names__whitespace
      CHECK (
             Names NOT LIKE ' %'
             AND Names NOT LIKE '% '
             AND Names NOT LIKE '%  %'
            );

Also consider disallowing other characters (tab, carriage return, line feed, etc) that may cause problems.

It may also be a good time to split those Names into family_name, first_name, etc :)

onedaywhen