if exists (select * from sys.all_objects where name='GetOrgTree')
begin drop function GetOrgTree end go create function GetOrgTree (@OrgID int) returns @tb table (id int,Orgname varchar(20),ParentID int) as begin --注意这里的表名是上面新建的表 tb_menu --这条语句是插入跟@OrgName相同的这条记录 这里假设是天津 insert @tb select id,OrgName,ParentID from tabOrg where id = @OrgID --返回受上一语句影响的行数 while @@rowcount > 0 -- 将上次的ID做为查询条件在进行插入操作, --父ID在@tb中 现在@tb中的ID为 3 因为上面是天津 即where pid in (3) --并且id 不在@tb中 and id not in (3) --这里需要大家理解下 insert @tb select id,OrgName,ParentID from tabOrg where ParentID in (select id from @tb) and id not in (select id from @tb) --最后返回@tb return end--select * from dbo.GetOrgTree(1)