说我有一个这样的表:
CREATE TABLE table1
(
CreatedAt DAteTimeOffset NULL
);
如何在while
循环中插入该表500行,并每5秒发送一次日期?我希望我的结果像这样:
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
以此类推...
我在这里有一个while循环,但是我不知道如何实现每5秒插入一次具有值的连续行。
DECLARE
@i int = 0
WHILE @i < 500
BEGIN
INSERT INTO table1
(CreatedAt)
VALUES
(?)
END
答案 0 :(得分:4)
尝试使用基于集合的方法。通常更快:
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
如果确实需要循环(不推荐使用),则可以使用以下代码:
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
答案 1 :(得分:0)
我认为Zohar就是这个解决方案
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