Manonia,
Не знаю что на самом деле вам нужно точно, просто попытаюсь предположить.
В следущем скрипте в пределах акаунта все записи будут переписываться/добавляться и удаляться будут те которых нет в переданом наборе (source). Записи остальных акаунтов будут не тронуты.
Можно это все написать и через update/insert/delete если эти операторы более знакомы вам.
-- подготовим таблицу
create table dbo.Accounts_Routes (
AccountID int
, RoutingCode int not null
, Priority int not null
, OmniBusAccountID int null
)
go
-- тесты
-- что было в таблице
select * from dbo.Accounts_Routes
declare @AccountID int = 10153253
declare @SourceTest table (
RoutingCode int not null
, Priority int not null
, OmniBusAccountID int null
)
insert into @SourceTest
values ( 620, 14, 10118786 )
, ( 621, 10, 1011 )
, ( 622, 11, 18786 )
;with cteTarget
as (
select *
from dbo.Accounts_Routes
where AccountID = @AccountID -- фильтр по акаунту, удалять данные в остальных акаунтах нельзя
)
merge cteTarget as t
using
( select RoutingCode
, Priority
, OmniBusAccountID
from @SourceTest
) as s ( RoutingCode, Priority, OmniBusAccountID )
on t.RoutingCode = s.RoutingCode
and t.Priority = s.Priority
when matched -- если совпало
then update
set OmniBusAccountID = s.OmniBusAccountID
when not matched -- если не совпало
then insert (
AccountID
, RoutingCode
, Priority
, OmniBusAccountID
)
values ( @AccountID
, s.RoutingCode
, s.Priority
, s.OmniBusAccountID
)
when not matched by source -- удаляем лишнее в пределах акаунта
then delete;
go
-- что получилось
select * from dbo.Accounts_Routes