如何在SQL中的循环中向表中插入300次?

时间:2021-07-01 09:09:19

I would like to insert a value retrieved from a counter in SQL and repeat it 300 times.

我希望在SQL中插入从计数器检索到的值,并重复300次。

Something like:

喜欢的东西:

DECLARE @Counter = 0;

-- BEGIN Loop 
    SET @Counter = @Counter + 1 
    INSERT INTO tblFoo VALUES(@Counter)
-- REPEAT 300 times

How can I achieve this? Thanks

我如何做到这一点?谢谢

4 个解决方案

#1


17  

You may try it like this:

你可以这样尝试:

DECLARE @i int = 0
WHILE @i < 300 
BEGIN
    SET @i = @i + 1
    /* your code*/
END

#2


9  

DECLARE @first AS INT = 1
DECLARE @last AS INT = 300

WHILE(@first <= @last)
BEGIN
    INSERT INTO tblFoo VALUES(@first)
    SET @first += 1
END

#3


4  

I would prevent loops in general if i can, set approaches are much more efficient:

如果可以的话,我一般会避免循环,集合方法会更有效:

INSERT INTO tblFoo
  SELECT TOP (300) n = ROW_NUMBER()OVER (ORDER BY [object_id]) 
  FROM sys.all_objects ORDER BY n;

Demo

演示

Generate a set or sequence without loops

生成一个没有循环的集合或序列

#4


1  

In ssms we can use GO to execute same statement

在ssms中,我们可以使用GO执行相同的语句

Edit This mean if you put

编辑这意味着如果你放

 some query

 GO n

Some query will be executed n times

一些查询将被执行n次

#1


17  

You may try it like this:

你可以这样尝试:

DECLARE @i int = 0
WHILE @i < 300 
BEGIN
    SET @i = @i + 1
    /* your code*/
END

#2


9  

DECLARE @first AS INT = 1
DECLARE @last AS INT = 300

WHILE(@first <= @last)
BEGIN
    INSERT INTO tblFoo VALUES(@first)
    SET @first += 1
END

#3


4  

I would prevent loops in general if i can, set approaches are much more efficient:

如果可以的话,我一般会避免循环,集合方法会更有效:

INSERT INTO tblFoo
  SELECT TOP (300) n = ROW_NUMBER()OVER (ORDER BY [object_id]) 
  FROM sys.all_objects ORDER BY n;

Demo

演示

Generate a set or sequence without loops

生成一个没有循环的集合或序列

#4


1  

In ssms we can use GO to execute same statement

在ssms中,我们可以使用GO执行相同的语句

Edit This mean if you put

编辑这意味着如果你放

 some query

 GO n

Some query will be executed n times

一些查询将被执行n次