How to find first and last occurrence of any char or word in sql query?

How to find first and last occurrence of any char or word in sql query? 


  • Find First occurrence of any character or word in the string :
In the given below example, we need to search for the first occurrence of word ‘the’ in the sentence.
DECLARE @String AS VARCHAR(100)
DECLARE @strSearch AS VARCHAR(100)
SET @String ='Hi SQL SERVER is from Microsoft'
SET @strSearch ='Hi'
--Find First occurrence of any character or word in the string
SELECT CHARINDEX(@strSearch ,@String) As [Result]

--OUTPUT
First occurrence
___________________
1

  • Find Last occurrence of any character or word in the string :
In the example given below, we need to search for the last occurrence of word‘the’ in the sentence.
DECLARE @String AS VARCHAR(100)
DECLARE @strSearch AS VARCHAR(100)
SET @String ='The SQL SERVER is from Microsoft hi'
SET @strSearch ='hi'
--Find Last occurrence of any character or word in the string
SELECT DATALENGTH(@String)-CHARINDEX(REVERSE(@strSearch )
,REVERSE(@String))-1 As [Result]
–OUTPUT Last occurrence
_________________________
33

Published by arjunpremier

Software Engineer, Blogger,

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Design a site like this with WordPress.com
Get started