sql >> Database teknologi >  >> RDS >> Sqlserver

Sådan får du antallet af rækker indsat af en transaktion

@@ROWCOUNT vil angive antallet af rækker, der er påvirket af den sidste SQL-sætning, er det bedst at indfange den i en lokal variabel efter den pågældende kommando, da dens værdi vil ændre sig, næste gang du ser på den:

DECLARE @Rows int
DECLARE @TestTable table (col1 int, col2 int)
INSERT INTO @TestTable (col1, col2) select 1,2 union select 3,4
SELECT @example@sqldat.com@ROWCOUNT
SELECT @Rows AS Rows,@@ROWCOUNT AS [ROWCOUNT]

OUTPUT:

(2 row(s) affected)
Rows        ROWCOUNT
----------- -----------
2           1

(1 row(s) affected)

du får Rows værdien 2, antallet af indsatte rækker, men ROWCOUNT er 1, fordi SELECT @example@sqldat.com@ROWCOUNT kommando påvirket 1 række

hvis du har flere INDSÆT eller OPDATERINGER osv. i din transaktion, skal du bestemme, hvordan du vil "tælle", hvad der foregår. Du kan have en separat total for hvert bord, en enkelt total værdi eller noget helt andet. Du skal ERKLÆRE en variabel for hver total, du vil spore og tilføje til den efter hver handling, der gælder for den:

--note there is no error handling here, as this is a simple example
DECLARE @AppleTotal  int
DECLARE @PeachTotal  int

SELECT @AppleTotal=0,@PeachTotal=0

BEGIN TRANSACTION

INSERT INTO Apple (col1, col2) Select col1,col2 from xyz where ...
SET @example@sqldat.comexample@sqldat.com@ROWCOUNT

INSERT INTO Apple (col1, col2) Select col1,col2 from abc where ...
SET @example@sqldat.comexample@sqldat.com@ROWCOUNT

INSERT INTO Peach (col1, col2) Select col1,col2 from xyz where ...
SET @example@sqldat.comexample@sqldat.com@ROWCOUNT

INSERT INTO Peach (col1, col2) Select col1,col2 from abc where ...
SET @example@sqldat.comexample@sqldat.com@ROWCOUNT

COMMIT

SELECT @AppleTotal AS AppleTotal, @PeachTotal AS PeachTotal


  1. H2 runscript-kommando gør alle tabelnavne til store bogstaver

  2. Ugyldigt tegn i SQL-forespørgselsstreng (ORA-00911)

  3. Tilføjer manglende datoer fra kalendertabellen

  4. PHP Sortering af nærmeste koordinater