这是本人项目当中的其中一个经典案例不使用临时表递归了表数据
使用with t 写法可以避免临时表创建减少了内存的使用和加快了数据的查询少了很多不必要的步骤使用递归更好的节约了前端部分加载速度
组织结构查询(由上级查询至下级组织结构不带人)
;WITH CREMyOrgTree
AS (SELECT A.My_Org_KeyId,A.My_Org_PKeyId,A.My_Org_SKeyId,A.My_Org_PName,A.My_Org_SName,A.My_Order,A.My_Org_SCode,A.My_Org_PCode
FROM MyOrgs A
WHERE A.My_Cocode=@My_Cocode AND A.My_Org_SKeyId = @My_Apply_OrgId AND A.My_Status=1
UNION ALL
SELECT A.My_Org_KeyId,A.My_Org_PKeyId,A.My_Org_SKeyId,A.My_Org_PName,A.My_Org_SName,A.My_Order,A.My_Org_SCode,A.My_Org_PCode --第二个查询作为递归成员, 下属成员的结果为空时,此递归结束。
FROM
CREMyOrgTree INNER JOIN MyOrgs A ON A.My_Cocode=@My_Cocode AND CREMyOrgTree.My_Org_SKeyId = A.My_Org_PKeyId AND A.My_Status=1)
SELECT distinct * INTO #temp2 FROM CREMyOrgTree ORDER BY My_Order;