本文介紹了獲取歷史記錄的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我有一個包含 RequestId
和 OldRequestId
兩列的表格.
I have the table with the two columns RequestId
and OldRequestId
.
如果我傳遞一個
RequestId
,它應該檢索我的特定記錄.
If I pass a
RequestId
, it should retrieve me the specific record.
如果檢索到的記錄中 OldRequestId
不為空,它也應該帶上舊的請求數據.
If the OldRequestId
is not null in the retrieved record, it should bring the old request data as well.
它應該一直持續到 OldRequestId
為空.
It should go on until the OldRequestId
is null.
有人可以幫我為這個需求寫出最好的 SQL 查詢嗎?
Can someone help me to write the best possible SQL query for this requirement?
推薦答案
您可以使用遞歸公用表表達式 (CTE) 解決此問題:
You can solve this using a recursive Common Table Expression (CTE):
DECLARE
@RequestID int = 6;
WITH
ReqCTE AS
(
SELECT
RequestID,
OldRequestID
FROM
Requests
WHERE
RequestID = @RequestID
UNION ALL SELECT
R.RequestID,
R.OldRequestID
FROM
ReqCTE C
INNER JOIN Requests R
ON R.RequestID = C.OldRequestID
)
SELECT
*
FROM
ReqCTE;
這篇關于獲取歷史記錄的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!