步步为营-82-获取当前部门的所有上级节点-存储过程实现
说明:需求部门表自身关联 表字段OrgUnitGUID(主键) OrgUnitName(名称) UpperOrgUnitGUID(自身关联)
通过存储过程实现.参考博客http://blog.csdn.net/apollokk/article/details/8330299
现将内容简画
1 演练
CREATE TABLE [dbo].[department]( [ID] [decimal](18, 0) IDENTITY(1,1) NOT NULL, [department] [nvarchar](20) NULL, [pid] [decimal](18, 0) NULL )
CREATE PROCEDURE [dbo].[getChildDeptById] @id INT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. -- SET NOCOUNT ON; WITH dept AS ( SELECT * FROM dbo.department WHERE pid = @id UNION ALL SELECT d.* FROM dbo.department d INNER JOIN dept ON d.pid = dept.id ) SELECT * FROM dept END
CREATE PROCEDURE [dbo].[getParentDeptById] @id INT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. -- SET NOCOUNT ON; WITH dept AS ( SELECT dp.* FROM dbo.department d INNER JOIN dbo.department dp ON d.pid=dp.ID WHERE d.id = @id UNION ALL SELECT d.* FROM dbo.department d INNER JOIN dept ON d.id = dept.pid ) SELECT * FROM dept END
2 实战
USE [ZLDC_CostControl] GO /****** Object: StoredProcedure [dbo].[SP_GetParentOrganizationUnitByOrgUnitGUID] Script Date: 2017/7/1 星期六 15:55:44 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: <yk> -- Create date: 2017年7月1日15:36:35 -- Description: 根据组织的GUID获取其所有的上级组织的名称 --使用场景:根据登录用户获取其所属机构的名称 (地产集团/集团总部 运营内控中心/信息管理) -- ============================================= ALTER PROCEDURE [dbo].[SP_GetParentOrganizationUnitByOrgUnitGUID] @OrgUnitGUID Nvarchar(50) AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. -- SET NOCOUNT ON; WITH dept AS ( SELECT dp.OrgUnitName ,d.OrgUnitGUID,d.UpperOrgUnitGUID FROM dbo.TB_OrganizationUnit d INNER JOIN dbo.TB_OrganizationUnit dp ON d.UpperOrgUnitGUID=dp.OrgUnitGUID WHERE d.OrgUnitGUID =@OrgUnitGUID UNION ALL SELECT d.OrgUnitName ,d.OrgUnitGUID,d.UpperOrgUnitGUID FROM dbo.TB_OrganizationUnit d INNER JOIN dept ON d.OrgUnitGUID = dept.UpperOrgUnitGUID ) SELECT * FROM dept END
//经办人部门的设置 //获取所有上级部门 通过存储过程 DataSet deptmentDS = TBContractSearch.GetParentOrganizationUnitByOrgUnitGUID(CurrentUser.OrganizationId); if (deptmentDS != null && deptmentDS.Tables[0].Rows.Count>0) { int count = deptmentDS.Tables[0].Rows.Count; StringBuilder deptNameSB = new StringBuilder(); for (int i = count-1; i > 0; i--) { deptNameSB.Append(deptmentDS.Tables[0].Rows[i]["OrgUnitName"]); deptNameSB.Append('/'); } string deptName = deptNameSB.ToString().TrimEnd('/'); this.attnDepart.Text = deptName;
3 运行效果
同一个表中有上下级关系,如果关系比较简单,或者获取的层级比较小的话可以通过表的连接实现
SELECT d.ObjID1,d.ObjName1 as 项目,d.ObjID2,d.ObjName2 as 区域 ,d2.ObjID2,d2.ObjName2 公司 FROM dbo.[MDS_Hr_ObjRelation] d , dbo.[MDS_Hr_ObjRelation] d2 WHERE d.ObjID1 = '3C20E046-D79E-447E-98B7-DE6A7472EC88' and d2.ObjID1=(SELECT d2.ObjID2 FROM dbo.[MDS_Hr_ObjRelation] d2 WHERE d2.ObjID1 = '3C20E046-D79E-447E-98B7-DE6A7472EC88')