2010-10-12 174 views
15

我是SQL Server開發新手。我的大部分經驗都是通過Oracle完成的。SQL Server遞歸查詢

假設我有一個包含約會下表對象

CREATE TABLE [dbo].[Appointments](
    [AppointmentID] [int] IDENTITY(1,1) NOT NULL, 
    ....... 
    [AppointmentDate] [datetime] NOT NULL, 
    [PersonID] [int] NOT NULL, 
    [PrevAppointmentID] [int] NULL, 
CONSTRAINT [PK_Appointments] PRIMARY KEY CLUSTERED ([AppointmentID] ASC) 

的約會可以推遲所以,當這一切發生時,與包含原始的ID的PrevAppointmentID字段的表創建一個新的行約定。

我想查詢一個人約會的歷史記錄。例如,如果ID = 1的任命推遲了兩次,並且這些延期已爲同一PersonID創建了ID = 7和ID = 12的約會,我想進行查詢以返回以下結果:

AppointmentID   PrevAppointmentID 
----------------- ---------------------- 
1      NULL 
7      1 
12     7 

如果使用Oracle,我記得使用CONNECT BY PRIOR子句可以得到類似這樣的東西。

有什麼辦法可以做出查詢來實現這些結果嗎?

我正在使用SQL Server 2005/2008。

在此先感謝

回答

18

考慮使用所謂的CTE(公共表表達式)(參見MSDN document):

;with cteAppointments as (
select AppointmentID, PersonID, PrevAppointmentID 
    from Appointments 
    where PrevAppointmentID is null 
union all 
select a.AppointmentID, a.PersonID, a.PrevAppointmentID 
    from Appointments a 
     inner join cteAppointments c 
      on a.PrevAppointmentID = c.AppointmentID 
) 
select AppointmentID, PrevAppointmentID 
    from cteAppointments 
    where PersonID = xxx