Assume there is a table of contract data, aptly named dbo.Contracts. Once a contract expires, a new row will be created in the table. I need to track the contract number of the old contract with the new contract. For example, contract number 123456 expires today. The application creates a renewal contract today (contract number 888888). Field dbo.Contracts.PreviousContractID for the row belonging to contract number 888888 gets updated to 123456.
That's all well. However, eventually over the years there will be a "chain" of contracts. 123456 renewed as contract 888888, which renewed as 999999, etc, etc.
----------------------------------------------------------------
Table dbo.Contracts
----------------------------------------------------------------
ContractID | Lots of other fields | PreviousContractID
----------------------------------------------------------------
123456 | | NULL
----------------------------------------------------------------
888888 | | 123456
----------------------------------------------------------------
999999 | | 888888
How would I write a query to say "given contract number 999999, query all contracts in the chain." I'm at a loss at where to start. I'm not even sure adding a field dbo.Contracts.PreviousContractID is even the right design.
Desired query would say, "For contract number 999999, get all the contracts in the 'chain'":
@ContractID = 999999
Result set:
----------
ContractID
----------
999999
----------
888888
----------
123456
----------
I'm not looking for a complete code solution, rather a bump in the right direction in design. This feels almost like a "recursive self-join", if there is such a thing, and I'm lost on it.