A
A
artshelom2021-08-04 13:05:08
SQL Server
artshelom, 2021-08-04 13:05:08

How to add data to 2 tables after merge?

I use SqlExpress 15.0.2080 It is
necessary after Merge into to Add the data.

-- Делаем загрузку данных на сервер openJson для примера
MERGE INTO [dbo].[Payments] t 
  USING (SELECT * FROM OPENJSON('[{"ID":135981,"TimeStamp":"2018-07-10T17:17:34.15","serverId":null}]') 
  with ([ID] int, [TimeStamp] datetime, [serverId] int)) j ON (t.[ID] = j.[serverId]) 
  WHEN MATCHED THEN update set  t.[TimeStamp] = j.[TimeStamp]
  WHEN NOT MATCHED THEN INSERT ([TimeStamp]) values (j.[TimeStamp]) 
  output $action, inserted.[ID], j.[ID], null, null;
-- из Merge мы получаем Id, который раньше был у данной строчки и новый Id в базе данных
insert into [dbo].[Sync_TableEntities]([TableName], [CreateTime], [LastUpdateTime], [OrganizationId], [ServerColumnId])
  OUTPUT inserted2.Id values('[dbo].[Payments]',
    GETDATE(), GETDATE(), '35bcffb3-d804-452a-bd9c-cfa9f5f72c79', inserted.[ID])
-- Нужно загрузить со новым ID в одну таблицу
insert into [dbo].[Sync_EntityClientModels]([TableName], [CreateTime], [LastUpdateTime], [OrganizationId], 
    [ClientColumnId], [TableEntityId], [ClientId])
  values('[dbo].[Payments]', GETDATE(), GETDATE(), '35bcffb3-d804-452a-bd9c-cfa9f5f72c79', j.[ID], inserted2.Id, 
    'dbf6d576-95bc-46ac-8d08-d13bc5f6123b')
-- И загрузить в другую таблицу со старым ID(из данных) и загрузить ID с предыдущей таблице

And is it possible to make a filter for $action on Insert?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin Tsvetkov, 2021-08-04
@artshelom

IF $action = 'INSERT' …
Guide .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question