How to TRIM a String in SQL Server

TRIM is a very popular string function in many SQL. But SQL Server does not have TRIM function directly. Instead of TRIM string function SQL Server provides us LTRIM and RTRIM function to remove specified prefix or suffix from a string. which is more sophisticated. You can also do the same functionality by using both LTRIM() and RTRIM() function together. To make you a good understand her I will show some example on TRIM string function. Hope it will help you.

SQL Syntax of TRIM function:
LTRIM(str): Removes all white spaces from the beginning of the string.
RTRIM(str): Removes all white spaces at the end of the string.

Using TRIM function in SQL Server:
Using LTRIM() Function:

SELECT LTRIM('     Using LTRIM String Function in SQL     ')+' some text' 'Output'

Output:
“Using LTRIM String Function in SQL some text”

Using RTRIM() Function:

SELECT RTRIM('     Using LTRIM String Function in SQL     ')+' some text' 'Output'
SELECT ' some text' + RTRIM('     Using LTRIM String Function in SQL     ') 'Output'

Output:
” Using LTRIM String Function in SQL some text”
” some text Using LTRIM String Function in SQL”

Using both RTRIM() and LTRIM() function to achieve TRIM Functionality:

SELECT LTRIM(RTRIM('     Using LTRIM String Function in SQL     '))+' some text' 'Output'
SELECT ' some text' + LTRIM(RTRIM('     Using LTRIM String Function in SQL     ')) 'Output'

Output:
“Using LTRIM String Function in SQL some text”
” some textUsing LTRIM String Function in SQL”

Have a look at below summary:
SQL Server Trim Function

Leave a Reply

Your email address will not be published. Required fields are marked *

AlphaOmega Captcha Classica  –  Enter Security Code