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 where id = @table1_id
Update Table2 set field2 = @new_value where id = @table2_id
Update Table3 set field3 = @new_value where id = @table3_id
Right now I am executing them seperately but as they are only used together I wonder if they could be located in just one SP.
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
                        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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With