The SUBSTRING() function returns part of a character, text, binary, or image expression.
Summary
SUBSTRING ( Expression , Start_Index , Length )
Expression: This is a character string,text, binary string, a column, or an expression that includes a column.
Start_Index: This is an integer value that specifies where the substring begins.
Length: This is a positive integer that specifies how many characters or bytes of the expression will be returned. If this value 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 |
The following example shows how to return a part of a string, in the following query we can get the some part of the EmpName from first character to third character.
SELECT Empname, SUBSTRING(Empname,1,3) AS ‘Employee Code’
FROM tbl_employee
Output Will be:
EmpName | Employee Code |
Ankur | Ank |
David | Dav |
John | Joh |
James | Jam |
Mohan | Moh |
Ram | Ram |