Friday, September 7, 2018

T-SQL – How to get the count of occurrence of a keyword in a string


If there is a requirement to check how many times a particular keyword comes in a string then below T-SQL Code will be helpful in getting occurrence count.

USE [MyDB]

GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



CREATE FUNCTION [dbo].[CountOccurancesOfString]
(
    @searchString nvarchar(max),
    @searchTerm nvarchar(max)
)
RETURNS INT
AS
BEGIN
    return (LEN(@searchString)-LEN(REPLACE(@searchString,@searchTerm,'')))/LEN(@searchTerm)
END


GO

--Executing the function
SELECT [dbo].[CountOccurancesOfString]('Life is beautiful,Life is not about finding yourself. Life is about creating yourself. so live life.' ,'Life')



                        -----------------End of Article-------------

1 comment:

  1. Kerala Pareeksha Bhavan has Developed / Adopted the 9th Class Curriculum and Syllabus By National Council of Educational Research and Training is an autonomous organisation, Students Download Kerala 9th Class new Syllabus 2022 for NCERT it is Very useful, Kerala 9th Class Syllabus Students get your 9th Class Study Material Useful by NCERT, So Students do not Confuse, Visit NCERT Official Website get Study Material All Subject Wise Pdf Format. Kerala 9th Class Students who are Looking Forward to Preparing for their Main Examination can refer to the Syllabus in order to Avoid any Confusion about the Chapters, Kerala 9th Class Syllabus New Syllabus 2022 can be a Useful Resource for Students to Effectively Learn and Prepare for Their Examination, we Suggested Simple steps to to Download Kerala 9th Class Syllabus 2022 for Malayalam, English Medium All Subject Pdf Download.

    ReplyDelete