Search code examples
sqlsql-serversql-server-2000

How to increment DateTime column by a second for every row?


Suppose that I have this Time value: 09:00:00

And I have a table with a column Time, and I have three records in it.

I want to update those 3 records with that time but with the Time value incremented in one second each time (for every record).

Something like this:

ColumnA   ColumnB
1         09:00:00
2         09:00:01
3         09:00:02

How can I do that?

My Solution:

After some time working on my own solution, this is what I came up with

update tor1
set ColumnB = dateadd(s,tor2.inc, ColumnB)
from table1 tor1
inner join (select ColumnA, ROW_NUMBER() OVER (Order by ColumnA) as inc from table1) tor2 on tor1.ColumnA=tor2.ColumnA

Solution

  • You don't specify any particular ordering.

    For undeterministic/undocumented results you could try the quirky update approach.

    CREATE TABLE table1
    (
        ColumnB datetime NULL
    );
    
    INSERT INTO table1 DEFAULT VALUES;
    INSERT INTO table1 DEFAULT VALUES;
    INSERT INTO table1 DEFAULT VALUES;
    
    DECLARE @ColumnB datetime;
    
    SET @ColumnB = '19000101 09:00:00';
    
    UPDATE table1
    SET @ColumnB = ColumnB = DATEADD(s, 1, @ColumnB);
    
    SELECT *
    FROM table1;
    
    DROP TABLE table1;
    

    Otherwise you will need to use a cursor or find some way of simulating ROW_NUMBER in 2000.