Is it possible to update the first 100 rows in sql (server)?

3
UPDATE tbl_venda
SET produto=1
WHERE produto=3

The problem is that there are more than 10,000 lines of sales and the pc hangs. I would if it was possible to make 100 in 100, 500 in 500, not to get heavy.

    
asked by anonymous 16.02.2017 / 16:11

5 answers

4

This is possible, just put a TOP(100) after the update, eg:

UPDATE top(100) tbl_venda
SET produto=1
WHERE produto=3
    
16.02.2017 / 16:14
3

If you just need to change the product code 3 to 1 in the lines of the tbl_venda table, as it is in the code that transcribed for this topic, then the solution is simple.

-- código #1
declare @Continua int, @tamBloco int;
set @tamBloco= 500;
set @Continua= 1;

while (@Continua > 0)
  begin
  --
  UPDATE top (@tamBloco) tbl_venda
    set produto= 1
    where produto = 3;
  -- 
  set @Continua= @@rowcount;
  -- pausa (10 segundos entre execuções: "pra não ficar pesado")
  waitfor delay '0:00:10';
  end;

In the code above, the @tamBloco variable tells you how many lines the update will take; to the desired value.

The UPDATE statement runs multiple times until there are no more rows to update.

    
16.02.2017 / 16:34
2

With TOP:

UPDATE top (100) tbl_venda
SET produto=1
WHERE produto=3

Source: link

    
16.02.2017 / 16:14
2

Use the reserved keyword as follows:

UPDATE top (100) tbl_venda
SET produto=1
WHERE produto=3
    
16.02.2017 / 16:15
2

Without the ORDER BY clause the setting of TOP does not make much sense. You need an order to know what is 'up' and 'down'

Although the accepted server is not guaranteed which records will be affected.

Something like this is more consistent.

;WITH CTE AS 
( 
SELECT TOP 100 * 
FROM TBL_VENDA WHERE PRODUTO=3 AND ID >= PROXIMO_ID
ORDER BY ID
) 
UPDATE CTE SET PRODUTO=1

The variable proximo_id starts with 0 in the first UPDATE and must assume other values as updates are being made, otherwise you can not give updates in the next records.

    
16.02.2017 / 16:30