In SQL Server, both LEFT() and RIGHT() functions work similarly to the SUBSTRING() function, these functions return the specified number of the characters from the appropriate end of the string.
The SUBSTRING() function can easily be used in place of the LEFT() function, but returning data from the right end of a string is much more easy to code without RIGHT() function.
Summery
LEFT ( chars_exp , Char_Len )
RIGHT ( chars_exp , Char_Len )
chars_exp can be a constant, variable, or column.
Char_Len is the positive integer type value the describe how many characters of the chars_exp will be returned. If integer_expression is negative, SQL Server returns an error.
Example:
Suppose we have a table ‘tbl_employee’
Table name: tbl_Employee
Employee Id | EmpName | Salary | Department |
1 | Ankur | 1200 | Sales |
2 | David | 3400 | Sales |
3 | John | 1500 | HR |
4 | James | 1200 | Production |
5 | Mohan | 4500 | Production |
6 | Ram | 2300 | HR |
See the following query ( we create a Employee code with the help of Employee name and Employee id).
SELECT EmpName,
CONVERT(CHAR(1),Employee Id) + ‘-‘ + LEFT(EmpName,3) AS “Employee Code”
FROM tbl_Employee
Output Will be:
EmpName | Employee Code |
Ankur | Ank-1 |
David | Dav-2 |
John | Joh-3 |
James | Jam-4 |
Mohan | Moh-5 |
Ram | Ram-6 |