Question

Is it possible, using pure SQL to count the number of x's in the following strings?

708258761XXXXXXXX00A  
708232761XXXXXXXXXXA

result when ran against the previous strings being

8
10

I could easily do this in code, but I'm looking for a pure T-SQL method for doing this.

The pattern will have varying numbers of X's depending on the product I'm looking at.

Put another way, What I'm looking for is a pure SQL way of counting the number of matches of a pattern.

In the above example, the input pattern is X. Using another example, with a search pattern of Ted the following could return a value of 3:

Ted is Ted because Ted is awesome!

Was it helpful?

Solution

I've added a variable named @pattern to store the search pattern string.

This calculates the number of matches by removing each instance of the pattern, determining the number of removed characters and then dividing the number of removed characters by the length of the search pattern.

DECLARE @pattern varchar(20) = 'Ted'

SELECT (Len(ColumnToSearch) - Len(Replace(ColumnToSearch, @pattern, ''))) / Len(@pattern)
AS Number_Of_Matches
FROM MyTable

If you need to do this calculation frequently, a function could easily be created based off of this.

OTHER TIPS

Great answer from Adam Porad but didn;t forget that LEN does not count trailing spaces:

DECLARE @pattern varchar(20) = 'Ted ';
SELECT LEN(@pattern) -- return 3

Use DATALENGTH instead:

DECLARE @pattern varchar(20) = 'Ted ';
DECLARE @ColumnToSearch VARCHAR(1000) = 'Ted is Ted because Ted is awesome!';

SELECT (DATALength(@ColumnToSearch) - DATALength(Replace(@ColumnToSearch, @pattern, ''))) / DATALength(@pattern),
       (Len(@ColumnToSearch) - Len(Replace(@ColumnToSearch, @pattern, ''))) / Len(@pattern),
       (Len(@ColumnToSearch) - Len(Replace(@ColumnToSearch, @pattern, ''))),
       Len(@ColumnToSearch),
       Len(@pattern)
AS Number_Of_Matches
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top