2010-02-16 48 views

回答

77

@@ ROWCOUNT將給出受上一條 SQL語句影響的行數,最好將它捕獲到有問題的命令後面的局部變量中,因爲下次查看它時它的值會發生變化:

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

OUTPUT:

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

(1 row(s) affected) 

你的Rows值2,插入的行數,但ROWCOUNT是1,因爲SELECT @[email protected]@ROWCOUNT命令影響的1行

如果在事務中有多個INSERT或UPDATE等,則需要確定如何「計數」發生了什麼。您可以爲每個表格單獨總計,單個總計值或完全不同的東西。你需要爲每個總要跟蹤並添加到它適用於它的每個操作之後的聲明一個變量:

--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 @[email protected][email protected]@ROWCOUNT 

INSERT INTO Apple (col1, col2) Select col1,col2 from abc where ... 
SET @[email protected][email protected]@ROWCOUNT 

INSERT INTO Peach (col1, col2) Select col1,col2 from xyz where ... 
SET @[email protected][email protected]@ROWCOUNT 

INSERT INTO Peach (col1, col2) Select col1,col2 from abc where ... 
SET @[email protected][email protected]@ROWCOUNT 

COMMIT 

SELECT @AppleTotal AS AppleTotal, @PeachTotal AS PeachTotal 
+1

不是使用'SELECT @Rows = @@ ROWCOUNT',我嘗試了'SET @Rows = @@ ROWCOUNT'並仍然收到相同的結果。謝謝你,好帖子! – MikeTeeVee

+0

僅供參考:_Even_在事務塊語句中封裝了INSERT語句,導致@@ RowCount被重置,因此我必須在調用Commit之前設置@Rows變量! – MikeTeeVee

+1

@MikeTeeVee通過使用'SELECT',您可以在單個語句中進行多個賦值,因此您可以輕鬆添加'SELECT @Rows = @@ ROWCOUNT,@ID = SCOPE_IDENTITY(),@Error = @@ ERROR'。使用'SET'你只能設置一個值。 'TRY CATCH'不需要捕捉'@@ ERROR',但我仍然使用'SELECT'。 –

2

如果你需要爲你的日誌/審計可以輸出條款進一步信息: 這樣,不僅保留了受影響的行數,還記錄了什麼。

作爲插入期間的輸出條款的例子: SQL Server list of insert identities

DECLARE @InsertedIDs table(ID int); 

INSERT INTO YourTable 
    OUTPUT INSERTED.ID 
     INTO @InsertedIDs 
    SELECT ... 

HTH

2

我找到答案至5月以前的職位。這裏是。

CREATE TABLE #TempTable (id int) 

INSERT INTO @TestTable (col1, col2) OUTPUT INSERTED.id INTO #TempTable select 1,2 

INSERT INTO @TestTable (col1, col2) OUTPUT INSERTED.id INTO #TempTable select 3,4 

SELECT * FROM #TempTable --this select will chage @@ROWCOUNT value