16

I am new to SQL Server development. Most of my experience has been done with Oracle.

suppose I have the following table that contains Appointments objects

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)

An appointment can be postponed so, when this happens, a new row is created on the table with the PrevAppointmentID field containing the ID of the original Appointment.

I would like to make a query to obtain the history of a Person appointments. For example, if the appoinment with ID = 1 is postponed two times, and these postponements have created appointments with ID = 7 and ID = 12 for the same PersonID, I would like to make a query that returns the following results:

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

If using Oracle I remember that something like this can be obtained using the CONNECT BY PRIOR clause.

Is there any way to make a query to achieve these results?

I am using SQL Server 2005/2008.

thanks in advance

1 Answer 1

19

Look into using what is called a CTE (common table expression) (Refer to 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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.