Multiple update statements in one StoredProcedure

后端 未结 4 1262
梦毁少年i
梦毁少年i 2021-01-17 23:05

I am wondering if it is possible to have multiple Update statements in a store procedure

Something like this:

Update Table1 set field1 = @new_value w         


        
相关标签:
4条回答
  • 2021-01-17 23:38

    Yes, that works fine.

    Also put this in the stored procedure before the updates:

    set nocount on
    

    This keeps the stored procedures from creating result sets for queries without a result. Otherwise each update will produce an empty result set that is sent back to the client.

    0 讨论(0)
  • 2021-01-17 23:46

    Below is the stored procedure with transaction , nocounton and multiple update queries.

     CREATE PROCEDURE prc_update (@table1_id INT, @table2_id INT, @table3_id INT, 
     @new_value INT)
     AS
     BEGIN
     BEGIN TRY
    
     Set Nocount ON
     Begin Transaction
     Save Transaction BeforeTransactionSavePoint
        UPDATE  Table1
        SET     field1 = @new_value
        WHERE   id = @table1_id
    
        UPDATE  Table2
        SET     field2 = @new_value
        WHERE   id = @table2_id
    
        UPDATE  Table3
        SET     field3 = @new_value
        WHERE   id = @table3_id
       Commit Transaction
    END TRY  
    BEGIN CATCH
    
    If @@TRANCOUNT > 0
    Rollback Tran BeforeTransactionSavePoint
    DECLARE  
     @ErMessage NVARCHAR(2048),  
     @ErSeverity INT,  
     @ErState INT  
    
     SELECT  
     @ErMessage = ERROR_MESSAGE(),  
     @ErSeverity = ERROR_SEVERITY(),  
     @ErState = ERROR_STATE()  
    
     RAISERROR (@ErMessage,@ErSeverity,@ErState )  
     END
    
    0 讨论(0)
  • 2021-01-17 23:58

    Yes, it's possible:

    CREATE PROCEDURE prc_update (@table1_id INT, @table2_id INT, @table3_id INT, @new_value INT)
    AS
    BEGIN
            UPDATE  Table1
            SET     field1 = @new_value
            WHERE   id = @table1_id
    
            UPDATE  Table2
            SET     field2 = @new_value
            WHERE   id = @table2_id
    
            UPDATE  Table3
            SET     field3 = @new_value
            WHERE   id = @table3_id
    END
    
    0 讨论(0)
  • 2021-01-18 00:00

    You should wrap those statments in transactions as well so that if one fails all are rolled back.

    0 讨论(0)
提交回复
热议问题