MS SQL TRIM

TRIM is a new MS SQL Server function introduced from MS SQL Server 2017.

It removes space characters from both sides (at the beginning/left and at the end/right) of the given string value. 

Before introduction of TRIM function in MS SQL Server 2017 it was possible to accomplish this task by using the combination of both LTRIM (left) and RTRIM (right) functions that were introduced in the world of MS SQL server much earlier.

There was also a possibility to use a custom CRL function (C# String.Trim()) but this approach isn’t probably the best and the quickest one.

Example:

-- input value
DECLARE @StringValue nvarchar(max) = '  remove spaces from both sides of this string  ';
-- string with spaces
SELECT @StringValue AS Result UNION ALL
-- old way before introducing TRIM
SELECT LTRIM(RTRIM(@StringValue)) AS Result UNION ALL
-- new way with TRIM
SELECT TRIM(@StringValue) AS Result;

*You can download the complete SQL Script with all examples from the post here: SQL Script.sql (438.00 bytes)