本文介紹了獲取歷史記錄的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
我有一個(gè)包含 RequestId
和 OldRequestId
兩列的表格.
I have the table with the two columns RequestId
and OldRequestId
.
如果我傳遞一個(gè)
RequestId
,它應(yīng)該檢索我的特定記錄.
If I pass a
RequestId
, it should retrieve me the specific record.
如果檢索到的記錄中 OldRequestId
不為空,它也應(yīng)該帶上舊的請(qǐng)求數(shù)據(jù).
If the OldRequestId
is not null in the retrieved record, it should bring the old request data as well.
它應(yīng)該一直持續(xù)到 OldRequestId
為空.
It should go on until the OldRequestId
is null.
有人可以幫我為這個(gè)需求寫出最好的 SQL 查詢嗎?
Can someone help me to write the best possible SQL query for this requirement?
推薦答案
您可以使用遞歸公用表表達(dá)式 (CTE) 解決此問(wèn)題:
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;
這篇關(guān)于獲取歷史記錄的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!