--写一个处理函数
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_cid]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[f_cid]
GO
/*--树形数据处理
查询指定id的所有子
--邹建 2003-12(引用请保留此信息)--*/
/*--调用示例
--调用(查询所有的子)
select a.*,层次=b.[level] from 客户表 a,f_cid(2)b where a.ID=b.ID
--*/
create function f_cid(
@id int
)returns @re table(ID int,[level] int)
as
begin
declare @l int
set @l=0
insert @re select @id,@l
while @@rowcount>0
begin
set @l=@l+1
insert @re select a.ID,@l
from 客户表 a,@re b
where a.父ID=b.ID and b.[level]=@l-1
end
return
end
go
--调用函数实现查询,查询id=1的客户及其他所有下属
select a.*,b.*
from 客户表 a,销售单_主表 b,f_id(1)c
where a.ID=c.ID
and b.客户ID=c.ID