The RTRIM()
function in SQL Server is used to remove trailing spaces (spaces at the end) from a string. It doesn't affect leading spaces (spaces at the beginning) or spaces within the string.
Syntax:
RTRIM(string_expression)
string_expression
: The string from which the trailing spaces will be removed. This can be a column, variable, or string literal.
Example:
1. Basic Usage:
SELECT RTRIM('Hello World ') AS TrimmedString;
Output:
TrimmedString
---------------
Hello World
In this example, the function removes the trailing spaces from the string 'Hello World '
.
2. Using RTRIM on a column:
Assume you have a table called Employees
with a column Name
that may have trailing spaces:
SELECT RTRIM(Name) AS TrimmedName
FROM Employees;
This query will return the Name
column with any trailing spaces removed.
3. Combining RTRIM with other functions:
You can combine RTRIM()
with other string functions such as LEN()
or TRIM()
(if supported) to clean up strings further.
Example: Removing both leading and trailing spaces (using LTRIM()
for leading spaces and RTRIM()
for trailing spaces):
SELECT RTRIM(LTRIM(Name)) AS CleanedName
FROM Employees;
Notes:
RTRIM()
only removes spaces (ASCII 32) at the end of the string.- It doesn’t remove other whitespace characters like tabs or non-breaking spaces.
- For removing both leading and trailing spaces, you can use
TRIM()
in SQL Server 2017 and later.
Let me know if you need more specific examples or details!
No comments:
Post a Comment