Usar a junção no servidor SQL 2012 para inserir / actualizar dados
estou a usar o servidor SQL 2012 e tenho duas tabelas com estrutura idêntica. Eu quero inserir novos registros da tabela 1 para a tabela 2 se eles ainda não existem na tabela 2.
Se já existem, quero actualizar todos os registos existentes na tabela 2.
Há umas 30 colunas nas minhas mesas e quero actualizá-las todas. Alguém pode ajudar com isto? Eu dei uma olhada em vários links postados na internet, mas não entendo como meu o depoimento deve parecer. 3
1 answers
Não é assim tão difÃcil....
Você precisa:
- uma tabela de origem (ou consulta) para fornecer dados
- uma tabela de destino para a fundir em
- uma condição em que estes dois quadros são verificados
- a statement what to do if a match (on that condition) is found
- a statement what to do if NO match (on that condition) is found
-- this is your TARGET table - this is where the data goes into
MERGE dbo.SomeTable AS target
-- this is your SOURCE table where the data comes from
USING dbo.AnotherTable AS source
-- this is the CONDITION they have to "meet" on
ON (target.SomeColumn = source.AnotherColumn)
-- if there's a match, so if that row already exists in the target table,
-- then just UPDATE whatever columns in the existing row you want to update
WHEN MATCHED THEN
UPDATE SET Name = source.Name,
OtherCol = source.SomeCol
-- if there's NO match, that is the row in the SOURCE does *NOT* exist in the TARGET yet,
-- then typically INSERT the new row with whichever columns you're interested in
WHEN NOT MATCHED THEN
INSERT (Col1, Col2, ...., ColN)
VALUES (source.Val1, source.Val2, ...., source.ValN);
12
Author: marc_s, 2016-06-12 06:49:47