语法:
MERGE INTO [your table-name] [rename your table here]
USING
(
[write your query here]
)[rename your query-sql and using just like a table]
ON
([conditional expression here] AND [...]...)
WHEN
MATCHED
THEN
[here you can execute some update sql or something else ]
WHEN
NOT MATCHED
THEN
[execute something else here ! ]
需求:
假设一个student表 有这种需求。如果学生ID存在则更改姓名。如果学生ID不存在 则插入学生信息。
student.sql
S_ID S_NAME S_AGE
1 李一 15
2 李二 15
3 李三 11
4 李四 12
5 李五 13
6 李六 14
test.sql
ID NAME TEL
1 aaa 234
2 bbb 234
3 ccc 234
4 ddd 333
5 王五 111
6 张三 22
7 李四 20
mergin into student s using (select id,name,tel from test)t on (s.id=t.id)
when matched then update set s.name=t.name
when not matched then insert (id,name,age)values(t.id,t.name,t.age)