0

我在 SPROC 中有插入语句(简化),如下所示

SET ROWCOUNT 100

WHILE(1=1)
BEGIN

  INSERT INTO table1
  SELECT *
  FROM table2
  WHERE some_condition
  -- EDIT: Realized forgot to include this following vital line that is causing issue
  SET @var = @var + @@ROWCOUNT    

  -- @@ROWCOUNT now takes on a value of 1, which will cause the following IF check to fail even when no lines are inserted

  IF(@@ROWCOUNT = 0)
  BEGIN
    BREAK
  END

END

但问题是,在任何操作之后,即使没有更多行适合 my some_condition@@ROWCOUNT也等于1,而不是0

当返回 0 行与我的匹配时,如何打破该循环some_condition

4

5 回答 5

7

“set”语句创建的行数为 1。您应该立即将 @@ROWCOUNT 保存到 @rowCount 变量中,并稍后使用该变量。

declare @rowCount int

WHILE(1=1)
BEGIN

  INSERT INTO table1
  SELECT *
  FROM table2
  WHERE some_condition
  -- EDIT: Realized forgot to include this following vital line that is causing issue
  SET @rowCount = @@ROWCOUNT
  SET @var = @var + @rowCount    

  -- @@ROWCOUNT now takes on a value of 1, which will cause the following IF check to fail even when no lines are inserted

  IF(@rowCount = 0)
  BEGIN
    BREAK
  END

END

此外,您可以通过最初将 @rowCount 设置为 -1 并将 WHILE 条件更改为 @rowCount <> 0 来简化。条件 BREAK 将不再需要。

于 2013-03-27T00:46:28.307 回答
0

另一种解决方案。这将检查每次迭代以查看最后插入的记录的 ID 是否已更改。如果它没有更改,则表明该迭代没有添加任何记录。

SET ROWCOUNT 100
declare @id int;
WHILE(1=1)

  INSERT INTO table1
  SELECT *
  FROM table2
  WHERE some_condition

  IF(@id= @@identity)
  BEGIN
    BREAK
  END
  set @id = @@identity;
END
于 2013-03-22T21:19:07.170 回答
0

试试这个解决方案:

第一个解决方案

@@ROWCOUNT在循环的条件下使用。

SET ROWCOUNT 100

  INSERT INTO table1
  SELECT *
  FROM table2
  WHERE some_condition  


WHILE(@@ROWCOUNT > 0)
BEGIN

  INSERT INTO table1
  SELECT *
  FROM table2
  WHERE some_condition  

END

第二个解决方案

使用goto.

SET ROWCOUNT 100

WHILE(1=1)
BEGIN

  INSERT INTO table1
  SELECT *
  FROM table2
  WHERE some_condition

  IF(@@ROWCOUNT = 0)
  BEGIN
    goto label
  END

END

label1:
print 'After lopp'
于 2013-03-25T14:31:22.567 回答
0

我认为您应该使用它select来获取@@rowcount变量。试试这个:

declare @number_of_rows int    

SET ROWCOUNT 100

WHILE(1=1)
BEGIN

  INSERT INTO table1
  SELECT *
  FROM table2
  WHERE some_condition

  SELECT @number_of_rows=@@ROWCOUNT

  IF (@number_of_rows = 0)
  BEGIN
     BREAK
  END
END
于 2013-03-25T15:12:59.350 回答
-6

实现了类似于 Moho 的解决方案,但用于SELECT代替SET存储@@ROWCOUNT.

于 2013-03-28T18:46:41.330 回答