Dear Deer
Dear Deer

Reputation: 543

Insert into table consecutive DateTime values every 5 secounds

Say I have a table like this :

CREATE TABLE table1
(
    CreatedAt   DAteTimeOffset  NULL
);

How can I insert into that table 500 row in a while loop and have each date every 5 secound ? I want my outcome result be like this :

2018-10-08 05:00:00.0000000 +00:00
2018-10-08 05:00:05.0000000 +00:00
2018-10-08 05:00:10.0000000 +00:00
2018-10-08 05:00:15.0000000 +00:00
2018-10-08 05:00:20.0000000 +00:00
2018-10-08 05:00:25.0000000 +00:00
2018-10-08 05:00:30.0000000 +00:00
2018-10-08 05:00:35.0000000 +00:00
2018-10-08 05:00:40.0000000 +00:00
2018-10-08 05:00:45.0000000 +00:00
2018-10-08 05:00:50.0000000 +00:00
2018-10-08 05:00:55.0000000 +00:00
2018-10-08 05:01:00.0000000 +00:00
2018-10-08 05:01:05.0000000 +00:00
2018-10-08 05:01:10.0000000 +00:00
2018-10-08 05:01:15.0000000 +00:00

and so on ...

I have a while loop here but I don't know how to achieve inserting consecutive rows with values every 5 sek.

DECLARE
    @i int = 0

WHILE @i < 500
BEGIN
    INSERT INTO table1
    (CreatedAt)
    VALUES
    (?)
END

Upvotes: 0

Views: 130

Answers (2)

GuidoG
GuidoG

Reputation: 12039

I think Zohar means this solution

declare @t table (CreatedAt datetime)

insert into @t 
select top 500 
       dateadd(second, (row_number() over (order by @@spid ) - 1) * 5, sysdatetime()) 
from   sys.objects 
  --cross join sys.objects a cross join sys.objects b 

select * from @t

Upvotes: 1

Paweł Dyl
Paweł Dyl

Reputation: 9143

Try to use set-based approach. It's usually much faster:

WITH N AS --generate 500 rows (1..500)
(
    SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) N
    FROM (VALUES (1),(2),(3),(4),(5)) A(A)
    CROSS JOIN (VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10)) B(B)
    CROSS JOIN (VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10)) C(C)
)
INSERT INTO table1 SELECT DATEADD(SECOND, (N-1)*5, SYSDATETIME()) FROM N

If you really, really need a loop (discouraged), you can use following:

DECLARE @i int = 0;
DECLARE @d DAteTimeOffset = SYSDATETIME();
WHILE @i<500
BEGIN
    INSERT table1 VALUES (@d);
    SET @d = DATEADD(second, 5, @d);
    SET @i += 1;
END

Upvotes: 4

Related Questions