1. 程式人生 > 其它 >Merge Into 語法支援

Merge Into 語法支援

KINGBASE 相容Oracle 語法,實現了merge into 的功能。以下以例子的形式,介紹merge into語法的使用。以下例子在V8R6 ,且 database_mode=oracle 環境下驗證過,database_mode=pg 不支援merge into 語法。

一、建立測試資料

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 createtablesource_table(s_idinteger,s_namechar(9)); createtabletarget_table(t_idinteger,t_name
char(9)); insertintosource_tablevalues(1,'s_a'),(2,'s_b'); insertintotarget_tablevalues(1,'t_a'),(3,'t_c'); test=#select*fromsource_table ; s_id | s_name ------+----------- 1 | s_a 2 | s_b (2rows) test=#select*fromtarget_table ; t_id | t_name ------+----------- 1 | t_a 3 | t_c (2rows)

二、測試例子

1、例子1

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 test=#begin; BEGIN test=# mergeintotarget_tableast test-# using source_tableass test-#on(t.t_id=s.s_id) test-#whenmatchedthenupdatesett.t_name=s.s_name test-#whennotmatchedtheninsertvalues(s.s_id,s.s_name); MERGE 2 test=#select*fromtarget_table
orderbyt_id; t_id | t_name ------+----------- 1 | s_a 2 | s_b 3 | t_c (3rows) test=#rollback; ROLLBACK

注意:更新的列不能是ON 條件中被引用的列。

2、例子2

更新時可以通過WHERE 條件指明要更新的行,條件中既可以包含源表的列,也可以包含目標表的列,當指明WHERE 條件且條件為假時,則不更新。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 test=#begin; BEGIN test=# mergeintotarget_tableast test-# using source_tableass test-#on(t.t_id=s.s_id) test-#whenmatchedthenupdatesett.t_name=s.s_namewheret.t_id=3 test-#whennotmatchedtheninsertvalues(s.s_id,s.s_name); MERGE 1 test=# test=#select*fromtarget_tableorderbyt_id; t_id | t_name ------+----------- 1 | t_a--沒有被更新 2 | s_b 3 | t_c (3rows) test=#rollback; ROLLBACK

3、例子3

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 test=#begin; BEGIN test=# mergeintotarget_tableast test-# using source_tableass test-#on(t.t_id=s.s_id) test-#whenmatchedthenupdatesett.t_name=s.s_name test-#deletewheret.t_name='s_a' test-#whennotmatchedtheninsertvalues(s.s_id,s.s_name); MERGE 3 test=#select*fromtarget_tableorderbyt_id; t_id | t_name ------+----------- 2 | s_b 3 | t_c (2rows) test=#rollback; ROLLBACK

DELETE 子句只刪除目標表和源表的ON 條件為真、並且是更新後的符合刪除條件的記錄,DELETE 子句不影響INSERT 項插入的行

三、Postgresql 實現類 merge into 的方法

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 test=#begin; BEGIN test=#withupsertas( test(#updatetarget_table test(#sett_name = source_table.s_name test(#fromsource_table test(#wheretarget_table.t_id = source_table.s_id test(# returning target_table.* test(# ) test-#insertintotarget_tableselect*fromsource_table test-#wherenotexists ( test(#select1 test(#fromupsert b test(#wheresource_table.s_id = b.t_id test(# ); INSERT0 1 test=#select*fromtarget_tableorderbyt_id; t_id | t_name ------+----------- 1 | s_a 2 | s_b 3 | t_c (3rows) test=#rollback; ROLLBACK