1. ホーム
  2. sql

[解決済み] UPDATE文の影響を受ける行数を返す

2022-12-17 02:39:44

質問

ストアドプロシージャ (SQL Server 2005) の UPDATE クエリによって影響を受けた行の数を結果セットとして取得するには、どうすればよいですか。

CREATE PROCEDURE UpdateTables
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    UPDATE Table1 Set Column = 0 WHERE Column IS NULL
    UPDATE Table2 Set Column = 0 WHERE Column IS NULL
    UPDATE Table3 Set Column = 0 WHERE Column IS NULL
    UPDATE Table4 Set Column = 0 WHERE Column IS NULL
END

では、リターン。

Table1    Table2    Table3    Table4
32        45        0         3

どのように解決するのですか?

CREATE PROCEDURE UpdateTables
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    DECLARE @RowCount1 INTEGER
    DECLARE @RowCount2 INTEGER
    DECLARE @RowCount3 INTEGER
    DECLARE @RowCount4 INTEGER

    UPDATE Table1 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount1 = @@ROWCOUNT
    UPDATE Table2 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount2 = @@ROWCOUNT
    UPDATE Table3 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount3 = @@ROWCOUNT
    UPDATE Table4 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount4 = @@ROWCOUNT

    SELECT @RowCount1 AS Table1, @RowCount2 AS Table2, @RowCount3 AS Table3, @RowCount4 AS Table4
END