日期:2014-05-18  浏览次数:20580 次

高分求一个SQL语句!
有一张EMPLOYEE表,里面有字段,员工ID,上级ID,
我要取出某一个员工的所有上级ID,注意(譬如,A的上级是B,B的上级是C,C的上级是D,那我要取得的A的所有上级应该是B,C,D),请问这个SQL语句怎样写啊!

------解决方案--------------------
--建立測試環境
Create Table EMPLOYEE
(员工ID Int,
上级ID Int)
Insert EMPLOYEE Select 60, null
Union All Select 61, null
Union All Select 62, null
Union All Select 64, 61
Union All Select 65, 61
Union All Select 66, 64
Union All Select 67, 64
Union All Select 68, 67
Union All Select 69, 62
Union All Select 70, 62
Union All Select 71, 70
Union All Select 72, 70
GO
--建立函數
Create Function GetParent(@员工ID Int)
Returns @Tree Table (员工ID Int, 上级ID Int)
As
Begin
Insert @Tree Select * From EMPLOYEE Where 员工ID = @员工ID
While @@Rowcount > 0
Insert @Tree Select A.* From EMPLOYEE A Inner Join @Tree B On A.员工ID = B.上级ID And A.员工ID Not In (Select 员工ID From @Tree) Where A.上级ID Is Not Null
Return
End
GO
--測試
Select 上级ID From dbo.GetParent(64) Order By 上级ID
Select 上级ID From dbo.GetParent(66) Order By 上级ID
GO
--刪除測試環境
Drop Table EMPLOYEE
Drop Function GetParent
--結果
/*
上级ID
61


上级ID
61
64
*/
------解决方案--------------------
--借用楼上数据.

CREATE TABLE EMPLOYEE
(员工ID Int,
上级ID Int)
Insert EMPLOYEE Select 60, null
Union All Select 61, null
Union All Select 62, null
Union All Select 64, 61
Union All Select 65, 61
Union All Select 66, 64
Union All Select 67, 64
Union All Select 68, 67
Union All Select 69, 62
Union All Select 70, 62
Union All Select 71, 70
Union All Select 72, 70
GO

DECLARE @id AS varchar(200)
SET @id= '71 ';
WITH TCTE(员工ID,上级ID)
AS
(
SELECT 员工ID,上级ID
FROM EMPLOYEE WHERE 员工ID=@id
UNION ALL
SELECT ta.员工ID,ta.上级ID
FROM EMPLOYEE TA INNER JOIN TCTE TB
ON TA.员工ID=TB.上级ID
)
SELECT * FROM TCTE WHERE 上级ID <> ' '

DROP TABLE EMPLOYEE

/*
员工ID 上级ID
----------- -----------
71 70
70 62

(2 行受影响)

*/
------解决方案--------------------
lz应该是要的一楼的结果吧!