Sunday, February 19, 2012

Get Number of rows Deleted

How do we get the number of rows deleted from a table?
@.@.rowcount is returning 0@.@.rowcount (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_globals_20vo.asp) returns the number of rows affected by the last successful statement executed by your spid. It only has meaning for the duration of one statment, then it is reset.

See the code for the gory details of how you can go worng ;)DECLARE @.i1 INT
, @.i2 INT

CREATE TABLE #foo (
fooID INT NOT NULL
)

INSERT INTO #foo (fooID)
SELECT 0 UNION SELECT 1 UNION SELECT 2 UNION
SELECT 3 UNION SELECT 4 UNION SELECT 5

SELECT * FROM #foo

DELETE FROM #foo WHERE 1 = fooID % 2

SELECT @.i1 = @.@.rowcount

DELETE FROM #foo

PRINT 'We''re working on it!'

SELECT @.i2 = @.@.rowcount

SELECT @.i1, @.i2

SELECT * FROM #foo

DROP TABLE #foo-PatP|||A true gentleman

Isn't that a fubar table?

No comments:

Post a Comment