First, we split the string by spaces in a. Then, take a variable count = 0 and in every true condition we increment the count by 1. Now run a loop at 0 to length of string and check if our string is equal to the word.
Searching from the start of a string expression. This example returns the first location of the string is in string This is a string , starting from position 1 (the first character) of This is a string . SELECT CHARINDEX('is', 'This is a string'); Here is the result set.
Here you go:
declare @string varchar(100)
select @string = 'sfdasadhfasjfdlsajflsadsadsdadsa'
SELECT LEN(@string) - LEN(REPLACE(@string, 'd', '')) AS D_Count
If you want to make it a little more general, you should divide by the length of the thing you're looking for. Like this:
declare @searchstring varchar(10);
set @searchstring = 'Rob';
select original_string,
(len(orginal_string) - len(replace(original_string, @searchstring, ''))
/ len(@searchstring)
from someTable;
This is because each time you find 'Rob', you remove three characters. So when you remove six characters, you've found 'Rob' twice.
For all you Sybase ASE 15 dinosaurs our there, you will need to replace '' with null, i.e.
SELECT LEN(@string) - LEN(REPLACE(@string, 'd', null)) AS D_Count
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With