The RIGHT() function in SQL Server is used to extract a specified number of characters from the right (end) of a given string.
Syntax:
RIGHT(string_expression, length)
- string_expression: This is the string (or column) from which you want to extract characters.
- length: This is the number of characters you want to extract from the right side of the string.
Example Usage:
-
Basic Example: Extract the last 3 characters from a string.
SELECT RIGHT('SQL Server', 3) AS ExtractedString;Result:
ExtractedString ---------------- ver -
Extracting from a Column: If you want to extract the last 4 characters from a column of data, you can apply
RIGHT()to that column.Example:
SELECT RIGHT(EmployeeName, 4) AS LastFourLetters FROM Employees;This will return the last 4 characters of the
EmployeeNamefor each row in theEmployeestable. -
Using with Numbers: The
RIGHT()function can also be used with numbers, but SQL Server will implicitly convert numbers to strings before applying the function.Example:
SELECT RIGHT(12345, 3) AS LastThreeDigits;Result:
LastThreeDigits --------------- 345
Notes:
- If the length specified is greater than the length of the string, SQL Server will return the entire string.
- If the length is 0 or a negative number, SQL Server will return an empty string (
'').
Example for length greater than string:
SELECT RIGHT('SQL', 10) AS Result;
Result:
Result
------
SQL
In this case, RIGHT() returns the entire string since the specified length exceeds the length of the string.
No comments:
Post a Comment