如何获取以前更改的特定数据记录?
从下面的记录中,我已经尝试过但不知道要这么做
DECLARE @l_MSISDN AS TABLE
(
ID INT IDENTITY(1,1),
Old NVARCHAR(50),
New NVARCHAR(50),
AuthDate DATETIME
)
INSERT INTO @l_MSISDN VALUES
('A','B',GETDATE()),
('B','C',GETDATE()),
('C','D',GETDATE()),
('R','T',GETDATE()),
('R','Q',GETDATE())
;WITH CTE AS
(
select New,OLD,AuthDate
from @l_MSISDN nolock
UNION ALL
SELECT * from cte
where New = OLD
)
select * from cte
order by AuthDate
Old New AuthDate
A B 2018-04-04 11:06:51.953
B C 2018-04-04 10:39:03.563
C D 2014-12-20 06:25:20.397
R T 2016-02-10 15:25:20.123
Q R 2015-09-21 15:25:20.330
我希望输出为
old new Authdate
A B 2014-12-20 06:25:20.397
B C 2015-09-21 15:25:20.330
C D 2016-02-10 15:25:20.123
我将输入D作为输入
答案 0 :(得分:2)
您的尝试并不太远。您还需要通过UNION ALL
来引用JOIN
中的原始表:
DECLARE @Start char(1) = 'D';
SELECT *
INTO #Temp
FROM (VALUES ('A', 'B', CONVERT(datetime,'2018-04-04T11:06:51.953')),
('B', 'C', CONVERT(datetime,'2018-04-04T10:39:03.563')),
('C', 'D', CONVERT(datetime,'2014-12-20T06:25:20.397')),
('R', 'T', CONVERT(datetime,'2016-02-10T15:25:20.123')),
('Q', 'R', CONVERT(datetime,'2015-09-21T15:25:20.330'))) V (Old, New, AuthDate);
WITH rCTe AS(
SELECT T.Old,
T.New,
T.AuthDate
FROM #Temp T
WHERE T.New = @Start
UNION ALL
SELECT T.Old,
T.New,
T.AuthDate
FROM #Temp T
JOIN rCTE r ON r.Old = T.New)
SELECT r.Old,
r.New,
r.AuthDate
FROM rCTe r;
DROP TABLE #Temp;