博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
sql 递归查询
阅读量:6571 次
发布时间:2019-06-24

本文共 1613 字,大约阅读时间需要 5 分钟。

创建数据库表:

USE [WechatSalesSystem]

GO

/****** Object: Table [dbo].[Employee] Script Date: 2016/12/13 14:41:55 ******/

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON

GO

CREATE TABLE [dbo].[Employee](

[EmployeeId] [int] IDENTITY(1,1) NOT NULL,
[ManagerId] [int] NULL,
[FirstName] [nvarchar](50) NULL,
[LastName] [nchar](50) NULL,
[Job] [nvarchar](50) NULL,
[ParentId] [int] NULL,
CONSTRAINT [PK_Employee_1] PRIMARY KEY CLUSTERED
(
[EmployeeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

查询子节点语句:

WITH EmployeeTree

AS (SELECT *
FROM Employee
WHERE EmployeeId =3 --第一个查询作为递归的基点(锚点)
UNION ALL
SELECT Employee.* --第二个查询作为递归成员, 下属成员的结果为空时,此递归结束。
FROM
EmployeeTree INNER JOIN Employee ON EmployeeTree.EmployeeId = Employee.ParentId)
SELECT *
FROM EmployeeTree

查询父节点语句:

with EmployeeTree AS

(
SELECT *,0 level from Employee where EmployeeId=3 
UNION ALL 
SELECT Employee.*,level+1 from EmployeeTree
JOIN Employee on EmployeeTree.parentid= Employee.EmployeeId
)
SELECT * from EmployeeTree where level=2;

 

查找从子节点到定级节点的路径:

with EmployeeTree as

(
select EmployeeId,ManagerId,FirstName,ParentId,cast(EmployeeId as varchar(100)) as fulltypeid
from Employee where EmployeeId=2--子节点
union all
select
b.EmployeeId,b.ManagerId,b.FirstName,b.ParentId,
cast(a.fulltypeid+','+cast(b.EmployeeId as nvarchar(100)) as varchar(100)) as fulltypeid
from
EmployeeTree a,--子节点数据集
Employee b --父节点数据集
where a.ParentId=b.EmployeeId --子节点数据集.parendID=父节点数据集.ID
)
select * from EmployeeTree ;

转载于:https://www.cnblogs.com/noert/p/6169886.html

你可能感兴趣的文章
php项目中常用的log日志记录方法
查看>>
Android--实现点击一次返回键返回桌面而不是退出应用
查看>>
LogParser 导入MSSQL
查看>>
左侧固定导航栏
查看>>
linux安装go环境并编写第一个go程序
查看>>
解决:laravel出现Please provide a valid cache path.
查看>>
[JAVA] String常用方法
查看>>
oracle
查看>>
兼容IE浏览器样式的html上传文件控件
查看>>
直接插入排序
查看>>
fstab中mount错误导致不能启动
查看>>
OSPF转发地址深入解析
查看>>
SQLServer的Top功能
查看>>
CentOS之crontab
查看>>
Nginx-Access日志格式
查看>>
【在线研讨-现场文字】《敏捷开发用户故事分类与组织结构(二期-3)》2012-07-03...
查看>>
F5扩展Synthesis架构实现可靠的应用与互联网访问
查看>>
Hyper-V 2012 R2 配置存储QoS
查看>>
易语言 --什么情况下 用许可证
查看>>
项目总结:凡事预则立,不预则废!
查看>>