Return number of rows affected by UPDATE statements

前端 未结 3 2002
暖寄归人
暖寄归人 2020-11-30 05:29

How can I get the number of rows affected by an UPDATE query in a Stored Procedure (SQL Server 2005), as a resultset. e.g.

CREATE PROCEDURE UpdateTables
AS
B         


        
3条回答
  •  既然无缘
    2020-11-30 06:01

    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
    

提交回复
热议问题