SQL SERVER – 2017 – How to Remove Leading and Trailing Spaces with TRIM Function?

A sheet of paper on a cutting board with its ragged edges being squared off by a steel rule.

TRIM Function has haunted SQL DBA for ages. If you have been using SQL Server for a while, you will totally agree with me over here. In this blog post we will see how the new feature TRIM of SQL Server 2017 works in few simple words. Now you can remove leading and trailing spaces with one function.

SQL Server DBAs and Developers have always dealt with SQL Strings and the leading and trailing spaces often makes them crazy. Well, personally, I am big believer of data quality and often leading and trailing spaces around strings are not useful.

In the earlier times developers used to two different functions LTRIM and RTRIM around the string to get necessary results. However now in SQL Server 2017 we have a new feature introduced which is TRIM(). This function works just like LTRIM and RTRIM together.

Let us first see a quick demonstration:

DECLARE @str VARCHAR(250)
SET @str =' SomeValue '
SELECT '\'+@str+'\' OriginalString, LEN (@str) OriginalLen,
'\'+TRIM(@str)+'\' TrimString, LEN(TRIM(@str)) TrimLen

Remove leading and trailing spaces.

When you run above script you can see that when we use function TRIM around the string it removes leading and trailing spaces. If you are using SQL Server 2017, you can use this feature. However, if you are using earlier version of SQL Server, I suggest you read my earlier blog post here which explains you how you can trim a string with the help of RTRIM and LTRIM.

Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.

SQL Function, SQL Scripts, SQL Server, SQL String
Previous Post
SQL SERVER – Introduction to Log Space Usage DMV – sys.dm_db_log_space_usage
Next Post
The sp_ Prefix: Finding Stored Procedures Named the Risky Way

Related Posts

2 Comments. Leave new

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.