0

Ive got the following script, which should count the number of characters declared in @Char that is found in @password but its not working, can anyone point me in the right direction?

Declare @password as varchar(25), @Result int = 0,  @Char varchar(max), @index BigInt = 0

Set @password = 'su8cd023m6!$^j3'

Set @Char = '%[a-z]%'

DECLARE @passwordLen int = len(@password)

SET @index = CHARINDEX(@password, @Char, @index)
While @index > 0
BEGIN
    SET @Result = @Result + 1;
    SET @index = CHARINDEX(@password, @Char, @index + @passwordLen)
END

Print @Result

The above should return 6 as there are 6 alpha characters in @password

7
  • Could you please provide a reference showing that CHARINDEX() accepts wild cards in an expressionToSearch?
    – PM 77-1
    Jul 13, 2016 at 15:40
  • I havn't got one, so guessing your gonna tell me it doesnt and that that is where im first going wrong?
    – Jeffrey
    Jul 13, 2016 at 15:41
  • 1
    This is Transact SQL. Which DB are you using? Jul 13, 2016 at 15:41
  • @Jeffrey as in SQL Server 2008? Jul 13, 2016 at 15:42
  • Correct, sorry for not giving the full name
    – Jeffrey
    Jul 13, 2016 at 15:42

2 Answers 2

2
Declare @password as varchar(25), @Result int = 0,  @Char varchar(max), @index BigInt = 0

Set @password = 'su8cd023m6!$^j3'

  WHILE PATINDEX('%[^A-z]%',@password)>0
        SET @password = STUFF(@password,PATINDEX('%[^A-z]%',@password),1,'') 

Set @Result = Len(@password)

Print @password
Print @Result
0

Using Numbers table..

declare @str varchar(max)
set @str='su8cd023m6!$^j3'

;With cte
as
(

select 
case when isnumeric (substring(@str,n,1)) =1 then 1 else 0 end as val
from dbo.numbers
where n<len(@str)
)
select count(*) from cte where val=1

Output:
6

you also can use TRY_CONVERT(From SQL 2012),since IsNumeric tendS to show some special characters as 1 in similar way..

;With cte
as
(

select 
case when try_convert(int,substring(@str,n,1)) is null  then 0 else 1 end as val
from dbo.numbers
where n<len(@str)
)
select count(*) from cte where val=1
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.