[英]Select all related records
I have a table (in SQL Server) that stores records as shown below.我有一个表(在 SQL Server 中)存储如下所示的记录。 The purpose for
Old_Id
is for change tracking. Old_Id
的目的是用于更改跟踪。
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
和更新的值,以及Old_Id
列中修改后的记录的 Id
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.当我搜索 id = 1 或 2 或 4 时,我想选择所有相关记录。
In this case I want see records the following ids: 1, 2, 4在这种情况下,我希望看到记录以下 ID: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)您可以使用递归公用表表达式 (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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.