Just one word of warning... LEN() will not count trailing spaces, so the following will (incorrectly) return a value of 7:
declare @string varchar(50)
set @string='///xxx ///'
select len(@string)-len(replace(@string,'/',''))
/* Returns 7 */
You could use DATALENGTH() instead of LEN()...
declare @string varchar(50)
set @string='///xxx ///'
select datalength(@string)-datalength(replace(@string,'/',''))
/* Returns 6 */
But that only works with VARCHAR... if the string were NVARCHAR, you'd get twice the value you want:
declare @string nvarchar(50)
set @string=N'///xxx ///'
select datalength(@string)-datalength(replace(@string,N'/',N''))
/* Returns 12 */
Perhaps the best way to avoid the trailing space problem is to go back to using LEN(), but trick it by adding a non-space trailing character and adjusting the final result by 1 like so:
declare @string varchar(50)
set @string='///xxx ///'
select len(@string)-len(replace(@string,'/','')+'*')+1
/* Returns 6 */
--Brad
commented on Jun 15 2011 6:04PM