This is exactly what the OUTPUT
clause in SQL Server 2005 onwards is excellent for.
EXAMPLE
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'
Results in the following being returned
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
In your particular case, since you cannot use aggregate functions with OUTPUT
, you need to capture the output of INSERTED.*
in a table variable or temporary table and count the records. For example,
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