简体   繁体   中英

Select all related records

I have a table (in SQL Server) that stores records as shown below. The purpose for Old_Id is for change tracking.

Meaning that when I want to update a record, the original record has to be unchanged, but a new record has to be inserted with a new Id and with updated values, and with the modified record's Id in Old_Id column

Id   Name    Old_Id  
---------------------
1    Paul     null
2    Paul      1
3    Jim      null
4    Paul      2
5    Tim      null 

My question is:

When I search for id = 1 or 2 or 4, I want to select all related records.

In this case I want see records the following ids: 1, 2, 4

How can it be written in a stored procedure?

Even if it's bad practice to go with this, I can't change this logic because its legacy database and it's quite a large database.

Can anyone help with this?

you can do that with Recursive Common Table Expressions (CTE)

WITH cte_history AS (
    SELECT       
        h.id, 
        h.name,
        h.old_id
        
    FROM       
        history h
    WHERE old_id IS NULL
      and id in (1,2,4)
    UNION ALL
    SELECT 
        e.id, 
        e.name,
        e.old_id
    FROM 
        history e
        INNER JOIN cte_history o 
            ON o.id = e.old_id
)
SELECT * FROM cte_history;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM