当前位置: 代码迷 >> Sql Server >> 怎样知道 知道 周次字段包含多少个1?(101010101010101010000000000000)请前辈指导!该怎么解决
  详细解决方案

怎样知道 知道 周次字段包含多少个1?(101010101010101010000000000000)请前辈指导!该怎么解决

热度:412   发布时间:2016-04-24 23:44:58.0
怎样知道 知道 周次字段包含多少个1?(101010101010101010000000000000)请前辈指导!
表:

周次
101010101010101010000000000000

怎样知道 知道 周次字段包含多少个1?


------解决方案--------------------
select len(replace(周次,'0',''))
------解决方案--------------------
最笨的办法了

想不到啥好方法



declare @i int,@temp int,@s varchar(100)
set @s='101010101010'
set @i=1
set @temp=0
while (@i<LEN(@s))
begin
if( SUBSTRING('101010101010',@i,1)='1')
begin
set @temp=@temp+1
end
set @i=@i+1
end
print @temp


------解决方案--------------------

declare @a varchar(255)
set @a='101010101010101010000000000000'
select len(@a)-LEN(REPLACE(@a,'1','')) as [1的的个数]
/*
1的的个数
---------------------
9
*/

------解决方案--------------------
给你写一个函数功能,任何情况下都可以用.
--创建函数
create function AccRepeat
(
     @str varchar(50),
     @sub varchar(50)
)
     returns int 
as 
begin
declare @pos int,
        @n int
select @n=0, @pos=charindex(@sub,@str) while(@pos<>0)
    begin
       select @str=right(@str,len(@str)-@pos),@pos=charindex(@sub,@str),@n=@n+1
       end
       return(@n)
       end
       go
--调用函数,你只需要传入两个参数就可以了
select dbo.AccRepeat('101010101010101010000000000000','1')