SQL RIGHT() Function
SQL RIGHT() function returns substring from right side of specified string from a given column. If any column cell contains NULL value then it returns output as NULL for that value.
Syntax
SELECT RIGHT (String, IntegerValue)
Below is a simple example for RIGHT() function where we are selecting four characters from left side of given string.
SELECT RIGHT('SQLServerLog', 3)
Now, we will consider examples from Student table.
Here we will select three characters from right side of FirstName column with below query.
SELECT RIGHT(FirstName, 3) AS NewColumn, FirstName FROM Student
As you can see, we have extracted right three characters from FirstName column with RIGHT() function. Similarly you can add more columns and add paddings to represent as code. We will see one more query.
SELECT 'XXXX' + RIGHT(FirstName, 3) + CAST(RollNumber AS varchar) + 'XXXX' AS CODE FROM StudentĀ
Here, we are selecting three characters from right side of FirstName column with RollNumber column and padding with ‘XXXX’ value on both side with new column name as CODE.
Reference: Manzoor Siddiqui [www.SQLServerLog.com]