In SQL Server puoi utilizzare @@ROWCOUNT funzione di sistema per restituire il numero di righe interessate dall'ultima istruzione T-SQL.
Ad esempio, se una query restituisce 4 righe, @@ROWCOUNT restituirà 4.
Esempio 1 – Selezione dei dati
Ecco un esempio di base per dimostrare come funziona.
SELECT * FROM Dogs;
SELECT @@ROWCOUNT; Risultato:
+---------+-----------+-----------+ | DogId | DogName | GoodDog | |---------+-----------+-----------| | 1 | Fetch | 0 | | 2 | Fluffy | 0 | | 3 | Wag | 0 | +---------+-----------+-----------+ (3 rows affected) +--------------------+ | (No column name) | |--------------------| | 3 | +--------------------+ (1 row affected)
In questo caso, il mio SELECT l'istruzione ha restituito 3 righe, quindi @@ROWCOUNT restituito 3.
Esempio 2 – Aggiornamento dei dati
Ecco un esempio di utilizzo di @@ROWCOUNT con un UPDATE istruzione per verificare se alcune righe sono state aggiornate o meno.
UPDATE Dogs
SET GoodDog = 1
WHERE DogId = 4
IF @@ROWCOUNT > 0
PRINT 'Your dog will be rewarded accordingly';
ELSE
PRINT 'A dog outside the system cannot be a good dog'
GO Risultato:
(0 rows affected) A dog outside the system cannot be a good dog
In questo caso, nessuna riga è stata aggiornata perché il DogId non esisteva nella tabella. Siamo stati in grado di utilizzare @@ROWCOUNT con un IF istruzione per restituire un messaggio appropriato all'utente.
Eccolo di nuovo, ma questa volta il cane esiste.
UPDATE Dogs
SET GoodDog = 1
WHERE DogId = 1
IF @@ROWCOUNT > 0
PRINT 'Your dog will be rewarded accordingly';
ELSE
PRINT 'A dog outside the system cannot be a good dog'
GO Risultato:
(1 row affected) Your dog will be rewarded accordingly
Set di dati estremamente grande?
Se ritieni che la quantità di righe interessate da un'istruzione sarà superiore a 2 miliardi, utilizza ROWCOUNT_BIG() invece.
Puoi usarlo allo stesso modo di @@ROWCOUNT viene utilizzato.
UPDATE Dogs
SET GoodDog = 1
WHERE DogId = 4
IF ROWCOUNT_BIG() > 0
PRINT 'Your dog will be rewarded accordingly';
ELSE
PRINT 'A dog outside the system cannot be a good dog'
GO Risultato:
(0 rows affected) A dog outside the system cannot be a good dog
Quando @@ROWCOUNT è Ripristina
Dichiarazioni come USE , SET <option> , DEALLOCATE CURSOR , CLOSE CURSOR , PRINT , RAISERROR , BEGIN TRANSACTION o COMMIT TRANSACTION reimposta il @@ROWCOUNT valore a 0 .
Esecuzione di SELECT @@ROWCOUNT da solo restituirà anche 0 .