SQL Server TRIM() FunctionThe TRIM() function removes the space character OR other specified characters from the start or end of a string. By default, the TRIM() function removes leading and trailing spaces from a string. Note: Also look at the LTRIM() and RTRIM() functions.
We can remove part of the string using REPLACE() function. We can use this function if we know the exact character of the string to remove. REMOVE(): This function replaces all occurrences of a substring within a new substring.
The TRIM function is used to remove trailing and leading spaces (char(32)) from a string of characters. This was introduced with SQL Server 2017.
By default, the TRIM function removes the space character from both the beginning and the ending ends of the string. This behavior is equivalent to LTRIM(RTRIM(@string)) .
SELECT LTRIM(RTRIM(Names)) AS Names FROM Customer
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
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 :)
SELECT LTRIM(RTRIM(Replace(Replace(Replace(name,' ',' '),CHAR(13), ' '),char(10), ' ')))
from author
in sql server 2008 r2 with ssis expression we have the trim function .
SQL Server Integration Services (SSIS) is a component of the Microsoft SQL Server database software that can be used to perform a broad range of data migration tasks.
you can find the complete description on this link
http://msdn.microsoft.com/en-us/library/ms139947.aspx
but this function have some limitation in itself which are also mentioned by msdn on that page. but this is in sql server 2008 r2
TRIM(" New York ") .The return result is "New York".
Extended version of "REPLACE":
REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(RTRIM(LTRIM(REPLACE("Put in your Field name", ' ',' '))),'''',''), CHAR(9), ''), CHAR(10), ''), CHAR(13), ''), CHAR(160), '') [CorrValue]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With