views:

888

answers:

3

Hi

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.

+4  A: 

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
Quassnoi
wow that is slightly embarrassing, I of course tried this and kept getting syntax errors and somehow draw the conclusion it wasn't possible this way, just tried it again and works perfect! Thanks :)
The real napster
@The real napster: Would you mark Quassnoi's answer as answer? Thanks.
Sung Meister
+3  A: 

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.

Guffa
+2  A: 

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

HLGEM