【问题标题】:Merge syntax error合并语法错误
【发布时间】:2014-09-05 15:34:51
【问题描述】:

我正在尝试使用合并语法,但它不起作用

请帮我解决这个问题

create table tgt(id int,name varchar(10),age int)
insert into tgt values(1,'x',21),(2,'y',22),(3,'z',23)

create table src(id int,name varchar(10),age int)
insert into src values(1,'x1',24),(2,'x2',27),(4,'y1',27),(5,'z1',29),(3,'z',23)

merge tgt t using src s 
on t.id=s.id 
when matched then update src s
    set s.id=t.id,
    s.name=t.name,
    s.age=t.age
when not matched then
insert(id,name,age) values(s.id,s.name,s.age);

错误信息

Msg 102, Level 15, State 1, Line 12
Incorrect syntax near 'src'.

【问题讨论】:

  • 我的回答能回答你的问题吗?如果是,请考虑接受。

标签: sql sql-server tsql


【解决方案1】:

您似乎对源和目标感到困惑。在when matched then update 之后不需要表名,并确保您更新的是target 表而不是source 表。

试试这个代码:

create table tgt(id int,name varchar(10),age int)
insert into tgt values(1,'x',21),(2,'y',22),(3,'z',23)

create table src(id int,name varchar(10),age int)
insert into src values(1,'x1',24),(2,'x2',27),(4,'y1',27),(5,'z1',29),(3,'z',23)

merge tgt t using src s 
on t.id=s.id 
when matched then 
    update 
    set t.id=s.id,
    t.name=s.name,
    t.age=s.age
when not matched then
    insert(id,name,age) values(s.id,s.name,s.age);

【讨论】:

    猜你喜欢
    • 2018-11-22
    • 2021-03-19
    • 2011-10-04
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-05
    相关资源
    最近更新 更多