sql 根据关系表查找相应的父子类的数据
2010-09-06 14:19
288 查看
Create Table A
(ID Int,
fatherID Int,
Name Varchar(10)
)
Insert A Select 1, NULL, 'tt'
union All Select 2, 1, 'aa'
union All Select 3, 1, 'bb'
union All Select 4, 2, 'cc'
union All Select 5, 2, 'gg'
union All Select 6, 4, 'yy'
union All Select 7, 4, 'jj'
union All Select 8, 7, 'll'
union All Select 9, NULL, 'uu'
union All Select 10, 9, 'oo'
GO
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
create Function [dbo].[GetParent](@ID Int)
Returns @Tree Table (ID Int, fatherID Int, Name Varchar(10))
As
Begin
Insert @Tree Select ID, fatherID, Name From A Where ID = @ID
While @@Rowcount > 0
Insert @Tree Select A.ID, A.fatherID, A.Name From A A Inner Join @Tree B On A.ID = B.fatherID And A.ID Not In (Select ID From @Tree)
Return
End
--測試
Select * From dbo.GetParent(4)
(ID Int,
fatherID Int,
Name Varchar(10)
)
Insert A Select 1, NULL, 'tt'
union All Select 2, 1, 'aa'
union All Select 3, 1, 'bb'
union All Select 4, 2, 'cc'
union All Select 5, 2, 'gg'
union All Select 6, 4, 'yy'
union All Select 7, 4, 'jj'
union All Select 8, 7, 'll'
union All Select 9, NULL, 'uu'
union All Select 10, 9, 'oo'
GO
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
create Function [dbo].[GetParent](@ID Int)
Returns @Tree Table (ID Int, fatherID Int, Name Varchar(10))
As
Begin
Insert @Tree Select ID, fatherID, Name From A Where ID = @ID
While @@Rowcount > 0
Insert @Tree Select A.ID, A.fatherID, A.Name From A A Inner Join @Tree B On A.ID = B.fatherID And A.ID Not In (Select ID From @Tree)
Return
End
--測試
Select * From dbo.GetParent(4)
相关文章推荐
- SQL高级语句-JOIN 用于根据两个或多个表中的列之间的关系,从这些表中查询数据。
- Oracle 删除重复数据只留一条 查询及删除重复记录的SQL语句 1、查找表中多余的重复记录,重复记录是根据单个字段(Id)来判断 select * from 表 wher
- 请使用PL/SQL来按父子层次关系查询出表的所有数据
- Oracle 删除重复数据只留一条 查询及删除重复记录的SQL语句 1、查找表中多余的重复记录,重复记录是根据单个字段(Id)来判断 select * from 表 wher
- 根据条件查找数组中的一条数据并放入缓存
- AIX下如何根据端口号查找相应的进程
- hibernate+java+sql 之间数据类型转换关系
- java.sql.Types,数据库字段类型,java数据类型的对应关系
- 根据库中的表自动生成数据字典的T-SQL脚本 ---转
- T-SQL 存储过程: (修订版) 根据基本表结构及其数据生成 INSERT INTO ... 的 SQL (转)
- [ActionScript 3.0] 根据xml属性查找相应xml节点,递归函数。
- sql查找两条以上的数据 having
- SQL 根据连续区间 生成数据。 区间拆分
- Oracle 与sql 数据类型对应关系
- 根据表名查找相应表结构
- 如何根据事物代码查找相应BAPI
- 关系数据标准语言SQL之数据查询
- 查找数据库中重复数据T-SQL
- Sql 根据时间段查询数据
- sql 游标例子 根据一表的数据去筛选另一表的数据