How To Check If A String Contains A Substring In SQL Server




Quick work during automation requires checking a specific word or character in a given statement in SQL Server, using CHARINDEX function will check if the string contains a specific substring with CHARINDEX function.

CHARINDEX(): This function is used to search for a specific word or a substring in an overall string and returns its starting position of the match. In case no word is found, then it will return 0 (zero).

Demo:


/******* Search existence of  string in main text ******************/
Declare @ParentString nvarchar(100)='Sumit Kumar Srivastava'
Declare @ChildString nvarchar(100)='Sumit'
Declare @OrphanString nvarchar(100)='Anuj' 

/* This code will confirm that child string is part of parent string*/ 
if CHARINDEX(@ChildString  ,@ParentString) > 0  
begin 
   select 'Child string is part of parent string' As Result 
end 
else 
    select 'Child string is not part of parent string' As Result

/* This code will confirm that child string is part of parent string*/
if CHARINDEX(@OrphanString  ,@ParentString) > 0  
begin 
   select 'Child string is part of parent string' As Result 
end 
else 
    select 'Child string is not part of parent string' As Result
/**************************************************************/

No comments:
Write comments

Please do not enter spam links

Meet US

Services

More Services