Esto es exactamente para lo que OUTPUT
es excelente la cláusula en SQL Server 2005 en adelante.
EJEMPLO
CREATE TABLE [dbo].[test_table](
[LockId] [int] IDENTITY(1,1) NOT NULL,
[StartTime] [datetime] NULL,
[EndTime] [datetime] NULL,
PRIMARY KEY CLUSTERED
(
[LockId] ASC
) ON [PRIMARY]
) ON [PRIMARY]
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 07','2009 JUL 07')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 08','2009 JUL 08')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 09','2009 JUL 09')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 10','2009 JUL 10')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 11','2009 JUL 11')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 12','2009 JUL 12')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 13','2009 JUL 13')
UPDATE test_table
SET StartTime = '2011 JUL 01'
OUTPUT INSERTED.* -- INSERTED reflect the value after the UPDATE, INSERT, or MERGE statement is completed
WHERE
StartTime > '2009 JUL 09'
Resulta en la devolución de lo siguiente
LockId StartTime EndTime
-------------------------------------------------------
4 2011-07-01 00:00:00.000 2009-07-10 00:00:00.000
5 2011-07-01 00:00:00.000 2009-07-11 00:00:00.000
6 2011-07-01 00:00:00.000 2009-07-12 00:00:00.000
7 2011-07-01 00:00:00.000 2009-07-13 00:00:00.000
En su caso particular, dado que no puede usar funciones agregadas con OUTPUT
, debe capturar la salida de INSERTED.*
en una variable de tabla o tabla temporal y contar los registros. Por ejemplo,
DECLARE @temp TABLE (
[LockId] [int],
[StartTime] [datetime] NULL,
[EndTime] [datetime] NULL
)
UPDATE test_table
SET StartTime = '2011 JUL 01'
OUTPUT INSERTED.* INTO @temp
WHERE
StartTime > '2009 JUL 09'
-- now get the count of affected records
SELECT COUNT(*) FROM @temp