更改此存储过程以避免使用 CROSS APPLY?
Change this stored procedure to avoid using CROSS APPLY?
我试图在不同的列中显示老板和他们负责的员工的名字。
我可以通过交叉应用来完成,但我被要求在不使用它的情况下进行,但我真的想不出该怎么做。
我正在为 SQL 服务器使用 Northwind 数据库,这是我的代码:
CREATE PROCEDURE sp_getBossAndEmployeeNames
@bossID NCHAR(5)
AS
CREATE TABLE #TEMP_BOSSES_AND_EMPLOYEES
(
BossFullName VARCHAR(35),
EmployeeFullName VARCHAR(35)
)
INSERT INTO #TEMP_BOSSES_AND_EMPLOYEES
SELECT (FirstName + ' ' + LastName) as BossFullName, sub.EmployeeFullName
FROM Employees
CROSS APPLY
(
SELECT (FirstName + ' ' + LastName) as EmployeeFullName FROM Employees WHERE ReportsTo = @bossID
) AS sub
WHERE EmployeeID = @bossID
SELECT * FROM #TEMP_BOSSES_AND_EMPLOYEES
只需使用 INNER JOIN
:
SELECT B.FirstName + ' ' + B.LastName AS BossFullName
, E.FirstName + ' ' + E.LastName AS EmployeeFullName
FROM dbo.Employees B
INNER JOIN dbo.Employees E ON E.ReportsTo = B.id
WHERE B.EmployeeID = @bossID;
据我所知,你甚至不需要临时 table。
我试图在不同的列中显示老板和他们负责的员工的名字。
我可以通过交叉应用来完成,但我被要求在不使用它的情况下进行,但我真的想不出该怎么做。
我正在为 SQL 服务器使用 Northwind 数据库,这是我的代码:
CREATE PROCEDURE sp_getBossAndEmployeeNames
@bossID NCHAR(5)
AS
CREATE TABLE #TEMP_BOSSES_AND_EMPLOYEES
(
BossFullName VARCHAR(35),
EmployeeFullName VARCHAR(35)
)
INSERT INTO #TEMP_BOSSES_AND_EMPLOYEES
SELECT (FirstName + ' ' + LastName) as BossFullName, sub.EmployeeFullName
FROM Employees
CROSS APPLY
(
SELECT (FirstName + ' ' + LastName) as EmployeeFullName FROM Employees WHERE ReportsTo = @bossID
) AS sub
WHERE EmployeeID = @bossID
SELECT * FROM #TEMP_BOSSES_AND_EMPLOYEES
只需使用 INNER JOIN
:
SELECT B.FirstName + ' ' + B.LastName AS BossFullName
, E.FirstName + ' ' + E.LastName AS EmployeeFullName
FROM dbo.Employees B
INNER JOIN dbo.Employees E ON E.ReportsTo = B.id
WHERE B.EmployeeID = @bossID;
据我所知,你甚至不需要临时 table。