Search code examples
t-sqlsap-ase

TSQL break loop when @@ROWCOUNT = 0


I have insert statements (simplified) in a SPROC like the following

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

But the issue is, after any operation even when no more rows fit my some_condition, @@ROWCOUNT is equal to 1, not 0.

How can I break that loop when there are 0 rows returned matching my some_condition?


Solution

  • Implemented solution similar to Moho, but used SELECT instead of SET to store @@ROWCOUNT.