The CHARINDEX function finds the position of the expression in another expression.
Syntax:
select charindex(Exptofind ,Exptosearch ,[Start_Position])
Example 1:
- select charindex('a','Rakesh') [Position]
- select charindex('H','Hello World') [Position]
- select charindex(' ','C# corner') [Position]
- select charindex('W','C# corner') [Position]
- select charindex('a', NULL)
- select charindex(NULL,'Rakesh')
- select charindex('o','Hello World',6)
Example 2:
- create table Employee
- (
- EmpId int identity(1,1) primary key,
- Empname varchar(100),
- Salary int not null,
- Deptid int constraint Dept_Fk references Department(DeptId)
-
- )
-
- insert into Employee
- select 'Rakesh',8000,1
- union all
- select 'raju',1000,2
- union all
- select 'Naresh',5000,1
- union all
- select 'Venkatesh',5800,3
-
- select * from Employee
Query 1:
To find the CHARINDEX position of "R" in the Empname column of the Employee table.
- select Empname,charindex('R',Empname) as [Position] from Employee
Query 2:
To find whose Empname(s) start with "R" using CHARINDEX.
- select * from Employee
- where charindex('R',Empname)=1