SQL Server RTRIM() Function

RTRIM() is a string function in SQL Server used to remove trailing spaces from a string.

Syntax

The syntax for the RTRIM() function is as follows:

RTRIM ( string_expression )

Here, string_expression represents the string from which you want to remove the trailing spaces. It can be a constant, variable or an expression.

Usage

In a database, sometimes a string field may contain unnecessary spaces, which can affect data retrieval and comparisons. In such cases, the RTRIM() function can be used to remove trailing spaces from the string and standardize the data.

Examples

Here are two examples of using the RTRIM() function:

Example 1

Assume you have an Employees table that includes two fields, Name and Address. Now, you want to retrieve all the records from the table where the address has no trailing spaces. You can use the following SQL statement:

SELECT *
FROM Employees
WHERE RTRIM(Address) = Address;

The result set will include all the employee records where the address has no trailing spaces.

Example 2

Assume you have a string variable @str that has a value of "Hello World " (with multiple trailing spaces). Now, you want to remove the trailing spaces from the string. You can use the following SQL statement:

SET @str = RTRIM(@str);

The result will be the string "Hello World" with no trailing spaces.

Conclusion

The RTRIM() function is a commonly used string function in SQL Server that can be used to remove trailing spaces from a string. By using this function, you can standardize the data in the database and avoid errors in data retrieval and comparisons.