sql >> Base de Datos >  >> RDS >> Sqlserver

Usando merge en SQL Server para actualizar una tercera tabla

Necesita almacenamiento temporal de la salida de la declaración de combinación y una declaración de actualización que usa la tabla temporal / variable de tabla.

-- Your table A, B and C
declare @A table(ID int, Col int)
declare @B table(ID int, Col int)
declare @C table(ID int, Col int)

-- Sample data
insert into @A values (1, 1),(2, 2)
insert into @B values (1, 0)
insert into @C values (1, 0),(2, 0)

-- Table var to store ouput from merge
declare @T table(ID int, Col int, Act varchar(10))

-- Merge A -> B
merge @B as B
using @A as A
on A.ID = B.ID
when not matched then insert (ID, Col) values(A.ID, A.Col)
when matched then update set Col = A.Col
output inserted.ID, inserted.Col, $action into @T;

-- Update C with rows that where updated by merge    
update C set
  Col = T.Col
from @C as C
  inner join @T as T
    on C.ID = T.ID and
       T.Act = 'UPDATE'

https://data.stackexchange.com/stackoverflow/qt/119724/