你的想法很重要-大家都来谈 (C)Copyright 2012 by WeiPt

用sqlserver的自定义函数直接获取多级部门全名

好久没写存储过程了,今日正好同事的开发需要,实现显示多级部门的部门全名称。

如 财务部/会计部/会计一部

 

 

部门表

 

人员表

 

函数 getOrgAllName

--OrgID 72  当前的部门ID
ALTER function [dbo].[getOrgAllName](@OrgID int)
returns nvarchar(500)
as
begin

--调试用
--declare @OrgID int
--set @OrgID=72

declare @oname nvarchar(50)
declare @fid int
declare @rtnValue nvarchar(500)

select @oname=orgname,@fid=parentid from sys_org where orgid=@OrgID 

if (@fid=0)
set @rtnValue=@oname 
else 
begin
	select @rtnValue=dbo.getOrgAllName(@fid)
	set @rtnValue=@rtnValue+'\'+@oname
end
--print @rtnValue
return @rtnValue
end

  

调用和测试结果

select UserID,USERNO,USERNAME,ORGID, dbo.getOrgAllName(OrgID) as 部门全称 from Sys_User

 

posted @ 2017-09-27 16:50  weipt  阅读(652)  评论(0编辑  收藏  举报

你的想法很重要-大家都来谈 (C)Copyright 2012 by WeiPt