日期:2014-05-17  浏览次数:20571 次

数据库同一张表部门递归查询部门总人数(急~~)
本帖最后由 xiaopingatrry 于 2012-12-14 16:11:56 编辑
表 table1
codes

KD01
KD01.0003
KD01.0003.0001
KD01.0003.0001.0001
KD01.0003.0001.0001.0001
KD01.0003.0001.0001.0002
KD01.0003.0001.0001.0003
KD01.0003.0001.0002
KD01.0003.0001.0003
KD01.0003.0001.0003.0001
KD01.0003.0001.0003.0003
KD01.0003.0001.0003.0004
KD01.0003.0001.0003.0005
KD01.0003.0001.0003.0007
KD01.0003.0001.0003.0009
KD01.0003.0001.0003.0010
KD01.0003.0001.0003.0012
KD01.0003.0001.0004
KD01.0003.0001.0005
KD01.0003.0001.0006
KD01.0003.0002
KD01.0003.0002.0001
KD01.0003.0002.0002
KD01.0003.0002.0002.0001
KD01.0003.0002.0002.0003
KD01.0003.0002.0002.0004
KD01.0003.0002.0002.0005
KD01.0003.0002.0003
KD01.0003.0002.0003.0001
KD01.0003.0002.0003.0002


如:部门 KD01.0003.0002
下面的部门为:
KD01.0003.0002.0002.0001
KD01.0003.0002.0002.0003
KD01.0003.0002.0002.0004
KD01.0003.0002.0002.0005
而我现在只要找到关于KD01.0003.0002
下有多少个部门 在关联人数即可

部门代码codes为上面的编码规则,怎么样一张表全部查询出一个部门的总人数,不是
select count(1) from table1 where codes like 'KD01%' 
这只能查出一条记录 我要全部记录 谢谢了~ 
------解决方案--------------------

declare @str nvarchar(100)
set @str='KD01.0003.0002'
select count(id) from #temp where charindex(@str,codes)>0

------解决方案--------------------
--> 测试数据:[table1]
if object_id('[table1]') is not null drop table [table1]
GO
create table [table1]([codes] varchar(24))
insert [table1]
select 'KD01' union all
select 'KD01.0003' union all
select 'KD01.0003.0001' union all
select 'KD01.0003.0001.0001' union all
select 'KD01.0003.0001.0001.0001' union all
select 'KD01.0003.0001.0001.0002' union all
select 'KD01.0003.0001.0001.0003' union all
select 'KD01.0003.0001.0002' union all
select 'KD01.0003.0001.0003' union all
select 'KD01.0003.0001.0003.0001' union all
select 'KD01.0003.0001.0003.0003' union all
select 'KD01.0003.0001.0003.0004' union all
select 'KD01.0003.0001.0003.0005' union all
select 'KD01.0003.0001.0003.0007' union all
select 'KD01.0003.0001.0003.0009' union all
select 'KD01.0003.0001.0003.0010' union all
select 'KD01.0003.0001.0003.0012' union all
select 'KD01.0003.0001.0004' union all
select 'KD01.0003.0001.0005' union all
select 'KD01.0003.0001.0006' union all
select 'KD01.0003.0002' union all
select 'KD01.0003.0002.0001' union all
select 'KD01.0003.0002.0002' union all
select 'KD01.0003.0002.0002.0001' union all
select 'KD01.0003.0002.0002.0003' union all
select 'KD01.0003.0002.0002.0004' union all
select 'KD01.0003.0002.0002.0005' union all
select 'KD01.0003.0002.0003' union all
select 'KD01.0003.0002.0003.0001' union all
select 'KD01.0003.0002.0003.0002'


select * from [table1] t
CROSS APPLY 
&nb