【问题标题】:Is it possible to merge a table in MSSQL with a view based on the same table?是否可以将 MSSQL 中的表与基于同一表的视图合并?
【发布时间】:2020-02-20 09:17:01
【问题描述】:

类似的东西

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 服务器足够智能来处理这个问题吗?

【问题讨论】:

  • “MS SQL 服务器是否足够聪明,可以处理这个问题?” 这不是有效的语法。您不能在 VIEW 中执行 DML 语句。
  • 当然合并不在视图内部。只是自动格式将它放在视图定义的正下方。两个步骤 - 1)创建视图,2)在合并中使用视图
  • @Larnu 是在开玩笑吗?抱歉,不确定...
  • 开什么玩笑,@Qlk ?
  • 不,我不是在开玩笑,@Qlk ;您不能VIEW 中执行 DML 语句。 MERGE 是一个 DML 语句。

标签: sql-server view merge


【解决方案1】:

可以在合并语句中使用视图(引用目标表):

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    • 2021-01-24
    • 2021-06-13
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多