用函数实现mysql和sqlserver的树查询

干活的时候 遇到要用sql语句做树查询(mysql和sqlserver) 这些思路都是我看其他兄弟姐妹的....能用但可能写得不怎么好  函数返回的都是以逗号分隔开的id字符串
mysql:
查询当前节点和他的祖先节点

CREATE DEFINER=`root`@`%` FUNCTION `org_getParents`(childId varchar(32)) RETURNS varchar(10000) BEGIN -- 获取机构父节点,包括本身 DECLARE sTemp VARCHAR(10000); DECLARE sTempParentId VARCHAR(10000); SET sTemp =childId; SET sTempParentId=childId; WHILE sTempParentId!='0' DO SELECT parent_id INTO sTempParentId FROM org where org_id=sTempParentId; IF sTempParentId is not null THEN SET sTemp = concat(sTemp,',',sTempParentId); END IF; END WHILE; RETURN sTemp; END

 

 

 查询当前节点和他的子孙节点

CREATE DEFINER=`root`@`%` FUNCTION `org_getChilds`(rootId varchar(32)) RETURNS varchar(10000) BEGIN -- 获取机构所有子节点,包括本身 DECLARE sTemp VARCHAR(10000); DECLARE sTempChd VARCHAR(10000); SET sTemp = rootId; SET sTempChd = rootId; WHILE sTempChd is not null DO SELECT group_concat(org_id) INTO sTempChd FROM org where FIND_IN_SET(parent_id,sTempChd) > 0; IF sTempChd is not null THEN SET sTemp = concat(sTemp,',',sTempChd); END IF; END WHILE; RETURN sTemp; END

 

 

 可以这样使用: select * from org where find_in_set(org_id,org_getChilds('1'));

 

 

 

select * from org where find_in_set(org_id,org_getParents('1'));

 
 

  sqlserver:

 

查询当前节点和他的祖先节点: CREATE FUNCTION [dbo].[org_getParents] ( -- Add the parameters for the function here @rootid varchar(50) ) RETURNS varchar(8000) AS BEGIN -- Declare the return variable here DECLARE @temp varchar(8000) DECLARE @tempid varchar(8000) -- Add the T-SQL statements to compute the return value here set @tempid=@rootid; set @temp=@rootid; while @tempid!='0' begin select @tempid=parent_id FROM org where org_id= @tempid; IF @tempid!='0' SET @temp =@temp+','+@tempid; end -- Return the result of the function RETURN @temp END

 

 

 查询当前节点和他的子孙节点 CREATE FUNCTION [dbo].[org_getChilds] ( -- Add the parameters for the function here @rootid varchar(50) ) RETURNS varchar(8000) AS BEGIN -- Declare the return variable here DECLARE @temp varchar(8000) -- Add the T-SQL statements to compute the return value here select @temp=org_id from org where org_id=@rootid while @@rowCount>0 select @temp=@temp+','+org_id from org where charindex(org_id,@temp)=0 and charindex(parent_id,@temp)>0 -- Return the result of the function RETURN @temp END

 

  可以这样用:

select * from org where charindex(org_id,dbo.org_getChilds('1'))>0
 

 

select * from org where charindex(org_id,dbo.group_getParents('1'))>0
 
 

 

 

你可能感兴趣的:(mysql,sqlserver)