从同一个表中选择父级和子级
我有一个 emp 表,
CREATE TABLE [dbo].[Emp](
[EmpId] [int] NULL,
[EmpName] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[ManagerId] [int] NULL
) ON [PRIMARY]
现在,将以下值插入到表中,
Insert Into Emp Values(1,'A',0)
Insert Into Emp Values(2,'B',1)
Insert Into Emp Values(3,'C',2)
Insert Into Emp Values(4,'D',2)
Insert Into Emp Values(5,'E',4)
Insert Into Emp Values(6,'F',4)
Insert Into Emp Values(7,'G',4)
Insert Into Emp Values(8,'H',6)
Insert Into Emp Values(9,'I',5)
Insert Into Emp Values(10,'J',7)
Insert Into Emp Values(11,'K',4)
我想在 select 语句中列出员工姓名及其经理姓名。
我现在正在做的是创建一个临时表,其中包含所有经理的姓名及其 ID。
然后根据Id从manager表中获取名字。
但我知道这不是正确的方法,事实上它很复杂。
I have a emp table,
CREATE TABLE [dbo].[Emp](
[EmpId] [int] NULL,
[EmpName] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[ManagerId] [int] NULL
) ON [PRIMARY]
Now, insert below values into the table
Insert Into Emp Values(1,'A',0)
Insert Into Emp Values(2,'B',1)
Insert Into Emp Values(3,'C',2)
Insert Into Emp Values(4,'D',2)
Insert Into Emp Values(5,'E',4)
Insert Into Emp Values(6,'F',4)
Insert Into Emp Values(7,'G',4)
Insert Into Emp Values(8,'H',6)
Insert Into Emp Values(9,'I',5)
Insert Into Emp Values(10,'J',7)
Insert Into Emp Values(11,'K',4)
I want to list employee name and their manager name in select statement.
What I am doing now is creating a temporary table which has all manager name and their Id.
Then getting the name from the manager table based on Id.
But I know this is not a correct way, in fact it is complex.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为此,您应该使用递归 CTE(通用表表达式):
You should use a recursive CTE (Common Table Expression) for this:
你是对的:你不必为此使用临时表。尝试使用递归查询。 查看 MSDN 上的此链接。有一个 ManagerId/EmployeeID 的示例。就像你的查询一样。
You are correct: you don't have to use a temporary table just for this. Try using recursive queries. Take a look at this link on MSDN. There is an example with ManagerId/EmployeeID. Just as in your query.