The following is a very simple logic to check the ocuurance of chars/word in a larger string. This thing is particularly important when you want to just check if the string that you are searching for occurs as a sub-string of a value in a larger string which may be a value of a column in a table.
One practicle example would be say for example you want to check if a role is there in a column of user_roles which has a comma separated value of all roles for a particular user, so here you know what you have to look for in a column of all roles.
DECLARE @LongSentence VARCHAR(MAX)
DECLARE @FindSubString VARCHAR(MAX)SET @LongSentence = 'My Super Long string with long words'SET @FindSubString = 'long'SELECT (LEN(@LongSentence) - LEN(REPLACE(@LongSentence, @FindSubString, ''))) CntReplacedChars,(One practicle example would be say for example you want to check if a role is there in a column of user_roles which has a comma separated value of all roles for a particular user, so here you know what you have to look for in a column of all roles.
DECLARE @LongSentence VARCHAR(MAX)
LEN(@LongSentence) - LEN(REPLACE(@LongSentence, @FindSubString, '')))/LEN(@FindSubString) CntOccuranceChars
In simple terms all it does is
Length of Long Seq (36) minus Length of Long Sentence with all 'long' replaced with blank (24) = 8 so we have 8 ocurrences of the characters
The above divided by the Length of 'long' will give you the occurrences of the word 'long' in the Long Sentence i.e 2
or 8/4 = 2
**I got the above T-SQL from this source http://blog.sqlauthority.com/2010/08/16/sql-server-finding-the-occurrence-of-character-in-string/
No comments:
Post a Comment