循环记录

时间:2012-11-30 11:26:49

标签: sql sql-server-2005 while-loop

我有一张表,其中包括下面这三列。这些是保存在DB中的ID更改,其中在这种情况下ID从1-> 2-> 3-> 4开始。

oldID    | newID   | added  
1        | 2       | 2012-11-23  
2        | 3       | 2012-11-24  
3        | 4       | 2012-11-25 
4        | 1       | 2012-11-26

我想要做的是发送oldID参数并返回newID,逐步完成更改。例如,如果我发送2,则返回1

我在下面的SQL查询中没有得到任何东西,因为我真的不知道我在做什么。

DECLARE @dateCurrent datetime
DECLARE @datePrevious datetime
DECLARE @oldID int
SET @dateCurrent = '1970-01-01'
SET @datePrevious = '1970-01-01'
SET @oldID = '2'

WHILE (@dateCurrent >= @datePrevious)
    BEGIN
        SELECT @oldID = newID, @datePrevious = added
        FROM theTable
        WHERE oldID = @oldID
    END

2 个答案:

答案 0 :(得分:1)

如果要递归,可以使用公用表表达式

例如:

;with cte as 
(
select *, 0 as level from yourtable
union all
select t1.old, cte.new, t1.dateadded, level + 1 from yourtable t1
    inner join cte on t1.new = cte.old
    and t1.dateadded<cte.dateadded
) 
    select old, new from 
    (select old, new, ROW_NUMBER() over (partition by old order by level desc) rn from cte)
    v 
    where rn=1

答案 1 :(得分:0)

我同意这可能看起来不是最好的解决方案,但我不打算改变自95年以来一直运行的系统中的某些内容。

我让它像这样工作:

DECLARE @dateCurrent datetime
DECLARE @datePrevious datetime
DECLARE @oldID int
SET @dateCurrent = '1970-01-01'
SET @datePrevious = '1970-01-01'
SET @oldID = '2'

WHILE (@datePrevious <= @dateCurrent )
BEGIN
SET @datePrevious = @dateCurrent 
SELECT @dateCurrent = t2.added, @oldID = t1.newID
from theTable
     inner join theTable t2
     on t2.oldID = t1.newID
     where t1.oldID = @oldID 
END
SELECT @oldID