How to update two tables in one statement in SQL Server 2005?

后端 未结 9 1588
轻奢々
轻奢々 2020-11-22 05:45

I want to update two tables in one go. How do I do that in SQL Server 2005?

UPDATE 
  Table1, 
  Table2
SET 
  Table1.LastName=\'DR. XXXXXX\', 
  Table2.WApr         


        
9条回答
  •  庸人自扰
    2020-11-22 05:55

    You can't update two tables at once, but you can link an update into an insert using OUTPUT INTO, and you can use this output as a join for the second update:

    DECLARE @ids TABLE (id int);
    BEGIN TRANSACTION
    
    UPDATE Table1 
    SET Table1.LastName = 'DR. XXXXXX'  
    OUTPUT INSERTED.id INTO @ids
    WHERE Table1.field = '010008';
    
    UPDATE Table2 
    SET Table2.WAprrs = 'start,stop' 
    FROM Table2 
    JOIN @ids i on i.id = Table2.id;
    
    COMMIT;
    

    I changed your example WHERE condition to be some other field than id. If it's id the you don't need this fancy OUTPUT, you can just UPDATE the second table for the same id='010008'.

提交回复
热议问题