Q:

SQL Looping for repeated value for next column?

Iam trying to loop my values so that my result must look like
       ETA              ETD
    01/01/2013       03/01/2013  //Adding Days according to condition, Here 1 day
    03/01/2013       06/01/2013  //Add 3 days
    06/01/2013       18/01/2013
    18/01/2013       21/01/2013

Here i need to loop values so that my value is repeated in next line
For this i have done my work as
    CREATE TABLE #TEMPETAETD(ROWNUM INT,ETA DATETIME,ETD DATETIME)
    CREATE TABLE #TEMPETD(ID INT IDENTITY(1,1),ETD DATETIME,ROWNUM INT)
    CREATE TABLE #TEMPETA(ID INT IDENTITY(1,1),ETA DATETIME,ROWNUM INT)
     ;WITH cte AS(
    SELECT Row_Number() OVER(ORDER BY Sequence)AS RowID,@ETA AS ETA,DATEADD(DD,vd.NumHaltDays,@ETD) as ETD FROM VoyageDetails vd WHERE ID=1 and vd.Sequence BETWEEN 0 AND 1)
   INSERT INTO #TEMPETAETD select * from cte
   DECLARE @C INT,@C1 INT
 SET @C=1

  WHILE @C<(SELECT COUNT(*) FROM #TEMPETAETD)
  BEGIN
 INSERT INTO #TEMPETA SELECT * FROM #TEMPETAETD WHERE ROWNUM=@C 
 SET @C=@C+1
 END

 SET @C1=2
  WHILE @C1<=(SELECT COUNT(*) FROM #TEMPETAETD)
  BEGIN
 INSERT INTO #TEMPETD SELECT * FROM #TEMPETAETD WHERE ROWNUM=@C1 
 SET @C1=@C1+1
 END

This is my condition for Looping..., Here i could not get my repeated values coming in next row.., Can any one please help

A:

It looks like you want values from both the current row and the row before it. In other words, you want to be able to pair up a row with the preceding row, and then select stuff from this pair.
I don't think you need loops for this. Looping is generally pretty slow.
The general idea is, like you did, number the rows. Then you can join the table to itself with the number. Below is an example of how you can do this pairing without using a loop. Schema: 
create table T (a int);
insert into T values
(1), (7), (20), (30), (500), (800), (1300), (2112);

query:
with tNumbered as (
  select row_number() over (order by a) as rowID, a
  from T 
)
select tLeft.a as l, tRight.a as r from tNumbered tLeft
left join tNumbered tRight on tLeft.rowID = tRight.rowID -1

Here's a fiddle showing it in action: http://sqlfiddle.com/#!3/a257a/2

