这正是OUTPUT
SQL Server 2005以后的子句最擅长的。
例
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'
结果返回以下内容
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
在您的特定情况下,由于您不能将聚合函数与一起使用OUTPUT
,因此您需要捕获INSERTED.*
表变量或临时表中的输出并计数记录。例如,
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