没有函数或游标的递归SQL联接?

没有函数或游标的递归SQL联接?,sql,sql-server-2005,select,recursive-query,Sql,Sql Server 2005,Select,Recursive Query,我有一张桌子,上面有刑事指控的清单。这些指控可以被取代。。例如,如果一名男子被指控犯有殴打罪,但在审判过程中受害者死亡,那么该指控将被替换为谋杀 我们有一个替换表,其中包含From_违规和To_违规。当费用被替换时,我们创建一个新费用,然后在替换表中记录From ID,然后记录new To_ID CREATE TABLE [dbo].[ijis_court_item_association]( [ijis_court_item_association_id] [int] IDENTITY

我有一张桌子,上面有刑事指控的清单。这些指控可以被取代。。例如,如果一名男子被指控犯有殴打罪,但在审判过程中受害者死亡,那么该指控将被替换为谋杀

我们有一个替换表,其中包含From_违规和To_违规。当费用被替换时,我们创建一个新费用,然后在替换表中记录From ID,然后记录new To_ID

CREATE TABLE [dbo].[ijis_court_item_association](
    [ijis_court_item_association_id] [int] IDENTITY(1,1) NOT NULL,
    [from_ijis_court_item_id] [int] NOT NULL,
    [to_ijis_court_item_id] [int] NOT NULL
)
一个电荷可以被多次替换。因此,电荷1变为电荷2,但后来电荷3。然后可能电荷3变成电荷4

你应该:

FROMID  TOID
1        2
2        3
3        4
要求基于当前费用ID返回费用ID列表

因此,在英语中,开发者将向我传递ChargeID:4,我需要返回该费用的历史记录(包括其自身)。我的结果是:

4
3
2
1
我可以做一个函数,GetPreviousChargeId,然后以某种方式递归地做一些事情?但是,我希望有一个聪明的方法来实现这一点


希望有办法。

我相信这应该行得通。如前所述,这是一个


看看这个:啊,在那里。玩得高兴哇,贾斯汀·皮奥尼,这似乎奏效了!我只是不知道这种逻辑是如何运作的。现在看看。我也不理解你的评论。不应该是精选4?谢谢Justin。太棒了!评论也很有帮助。我没有充分使用CTE,这很糟糕,但这显示了它们的威力。谢谢
WITH Charges AS
(
    --This should not be just a SELECT 4 because if no matches are found
    --then it will return a null and not recurse at all
    --This query will only run once at the beginning 
    --(it is the anchor to the recursion)
    SELECT to_ijis_court_item_id AS CourtID
    FROM ijis_court_item_association
    WHERE to_ijis_court_item_id = 4

    UNION ALL

    --This is the actual recursion, continuing to query until no results are found
    --It uses the first queries data to begin
    SELECT from_ijis_court_item_id AS CourtID
    FROM ijis_court_item_association
        JOIN Charges
            ON Charges.CourtID = ijis_court_item_association.to_ijis_court_item_id 
)
--This is the final output from all of the above queries (however many there are) 
--union all'ed together
SELECT * FROM Charges;