TSQL计算字符串中声明的字符数

时间:2016-07-13 15:34:30

标签: sql sql-server-2008

我有以下脚本,它应该计算@Char中声明的字符数量,这个字符在@password中找不到但是它不起作用,有人能指出我正确的方向吗?

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

上面应该返回6,因为@password中有6个字母字符

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

<强>输出:
6

你也可以使用TRY_CONVERT(来自SQL 2012),因为IsNumeric倾向于以类似的方式将一些特殊字符显示为1 ..

;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