SQL Server 递归查询
我是 SQL Server 开发新手。我的大部分经验都是通过 Oracle 完成的。
假设我有包含约会对象的下表,
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)
约会可以推迟,因此,当发生这种情况时,会在表上创建一个新行,其中 PrevAppointmentID 字段包含原始约会的 ID。
我想查询以获取某人的约会历史记录。例如,如果 ID = 1 的约会被推迟两次,并且这些推迟为同一 PersonID 创建了 ID = 7 和 ID = 12 的约会,我想进行一个返回以下结果的查询:
AppointmentID PrevAppointmentID
----------------- ----------------------
1 NULL
7 1
12 7
如果使用 Oracle我记得可以使用 CONNECT BY PRIOR 子句获得类似的东西。
有什么办法可以通过查询来达到这些结果吗?
我正在使用 SQL Server 2005/2008。
提前致谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
研究使用所谓的 CTE(公用表表达式)(请参阅 MSDN 文档):
Look into using what is called a CTE (common table expression) (Refer to MSDN document):