SQL_存储过程——获得一棵树的所有叶子节点
2015-06-24 15:31
141 查看
数据在数据库中的存储结构简化为:
A B1
A B2
B1 C1
B1 C2
B2 C3
B2 C4……
存储过程的代码如下:
CREATE PROCEDURE usp_test_GetLeavesOfTree ( @Parent nvarchar(255), @SR varchar(20) ) AS BEGIN declare @count int set @count=4 declare @ResultTable table(Terms nvarchar(255)) declare @TemTable table(Terms nvarchar(255)) insert @ResultTable select @Parent while @count>0 begin delete from @TemTable insert @TemTable select b.Term from Semantics,Glossary a,Glossary b,@ResultTable c where a.Term=c.Terms and a.Id=Semantics.T1 and b.Id=Semantics.T2 and SR=@SR union select c.Terms from @ResultTable c where not exists(select a.Term from Semantics,Glossary a where a.Id=Semantics.T1 and a.Term=c.Terms and SR=@SR) delete from @ResultTable insert into @ResultTable select* from @TemTable set @count=@count-1 end select * from @ResultTable order by Terms END
整体的思路为:根据根节点找到子节点,子节点找子子节点,其中要判断上一级节点是否为叶子节点如果是则添加到结果表中。叶子节点的特点就是只出现在第二列中,第一列中不存在。
相关文章推荐
- 解决Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in
- 数据库接口开发
- Redis笔记
- mysql远程登录权限不足问题解决
- (转)理解MySQL——索引与优化
- 修改Oracle数据库的字符集为UTF-8
- MySQL can’t specify target table for update in FROM clause
- MySQL优化之——自定义存储过程和函数
- mysql数据库隔离级别
- 如何启动/停止/重启MySQL
- Oracle11完全卸载方法
- zabbix使用自带模板监控mysql
- Mysql中的循环语句
- Oracle Job 语法和时间间隔的设定(转)
- 强制OPEN数据库后遭遇ORA-08102故障的处理方法
- SQL2008全部数据导出导入两种方法
- windows 8下配置PLSQLDeveloper
- mysql开启日志sql语句
- sql 根据状态自定义排序
- navicat导入.sql文件出错 2006 - MySQL server has gone away