Можно ли объединить таблицу в MS SQL с представлением, основанным на той же таблице? - PullRequest
0 голосов
/ 20 февраля 2020

Примерно так

create view V1 as 
select * from (T1 union T2) join T3 where "some condition on T3"

Then later in the process:
merge T2 using V1 
when not matched by Target then insert
when not matched by Source then delete

Достаточно ли умен сервер MS SQL, чтобы справиться с этим?

1 Ответ

0 голосов
/ 20 февраля 2020

Можно использовать представление (которое ссылается на целевую таблицу) в операторе слияния:

create table t1
(
    id int,
    colA int
)
go

create table t2
(
    id int,
    colB int
)
go

create view dbo.testview
as
select id, colB
from t2
except
select id, colA
from t1
go


insert into t2(id, colB) values (1, 2)
go

--populate t1 with the values of t2 (that do not exist yet in t1)
merge t1 as t
using testview as s on t.colA = s.colB
when not matched by target then 
insert(id, colA)
values(id, colB);
go
select *
from t2;
select *
from t1;
go

insert into t2(id, colB) values (1, 2)

merge t1 as t
using testview as s on t.colA = s.colB
when not matched by target then 
insert(id, colA)
values(id, colB);
go

select *
from t2;
select *
from t1;
go

drop view testview;
drop table t1;
drop table t2;
go
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...