M
M
Max Trophy2016-05-10 23:57:43
SQL Server
Max Trophy, 2016-05-10 23:57:43

I do Insert in a cycle, the condition of the termination of a cycle is registered, but for some reason does not come to an end?

CREATE PROC sp

AS

DECLARE @countrows int
SET @countrows = (select count(*) from таблица)

BEGIN
      insert into таблица (строка) values ( rand() )
WHILE 
      @countrows < 20

      IF @countrows > 20
      BREAK
   ELSE
      CONTINUE
    
END

It is assumed that if the number of rows in the table is less than 20 (determined by the count(*) function ), then the loop makes an insert, and so on until there are 20 rows.
The loop works, but only stops forcibly when it has already generated hundreds of rows (
What is the error in the code? ..
or maybe there are other ways to insert lines automatically? (there are only 20 of them in the example, but in life I need thousands of lines)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Artyom Karetnikov, 2016-05-12
@kapitoly

Well, why is it not limited to 20 - this is generally on the surface, the check is outside the cycle, but should be in it.
But to do so is not right - count is a rather heavy operation, and if, in addition, there are thousands of lines ... Declare a
variable and increment it
DECLARE @i INT = 0;
here is the
if @i > 20 loop -- here is the check
set @i = @i + 1; -- here increase
And any jerking of the server once again. This is the first moment.
The second point - if you just need to fill the table with test data, then there are solutions that not only do this, but also generate something similar to real data, it's more convenient, IMHO. The same ToolBelt can be viewed.

Алексей Лебедев, 2016-05-11
@swanrnd

CREATE PROC sp

AS

DECLARE @countrows int
SET @countrows = (select count(*) from таблица)

BEGIN
      insert into таблица (строка) values ( rand() )
WHILE 
      @countrows < 20
SET @countrows = (select count(*) from таблица)
      IF @countrows > 20
      BREAK
   ELSE
      CONTINUE
    
END

Как-то так

Константин Цветков, 2016-05-11
@tsklab Куратор тега SQL Server

Начать с простого:
SET NOCOUNT OFF

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question