在細(xì)節(jié)上,體現(xiàn)編程的修養(yǎng)。每一位大師,master,其基礎(chǔ)必定夯實(shí)。廢話不多說,直接上干貨,Merge子句用于對兩個(gè)數(shù)據(jù)表執(zhí)行數(shù)據(jù)同步,On子句指定匹配(when matched)條件,When子句指定額外的過濾條件和數(shù)據(jù)更新邏輯。源表(Source Table)和靶表(Targe Table)的數(shù)據(jù)行能夠匹配成功,這意味著on子句和when match條件都被滿足,進(jìn)入到when matched子句定義的更新代碼中,執(zhí)行數(shù)據(jù)同步操作;如果不滿足on子句,那么必須深入理解不匹配(when not matched)子句的條件,否則,很容易出錯(cuò)。首先查看MSDN對On子句的定義:

ON <merge_search_condition>  Specifies the conditions on which source_table_ is joined with target_table to determine where they match.

也就是說,如果兩個(gè)數(shù)據(jù)行滿足on子句條件,那么數(shù)據(jù)處理程序跳轉(zhuǎn)到when matched子句;如果兩個(gè)數(shù)據(jù)行不滿足on子句,那么數(shù)據(jù)處理程序跳轉(zhuǎn)到when not matched子句。如果在on子句中只指定源表列和靶表列之間的匹配關(guān)系,那么同步操作一般不會出現(xiàn)“意外"的問題,意外是指符合設(shè)計(jì)者的預(yù)期。一旦在on子句中試圖過濾靶表或源表的數(shù)據(jù)行,那么,再執(zhí)行數(shù)據(jù)同步可能出現(xiàn)異常結(jié)果,出現(xiàn)不符合設(shè)計(jì)者預(yù)期的行為。實(shí)際上,MSDN已經(jīng)明確給出提示,不要忽略這個(gè)提示,不然,你很可能已經(jīng)挖了坑而不自知:

It is important to specify only the columns from the target table that are used for matching purposes. That is, specify columns from the target table that are compared to the corresponding column of the source table. Do not attempt to improve query performance by filtering out rows in the target table in the ON clause, such as by specifying AND NOT target_table.column_x = value. Doing so may return unexpected and incorrect results.

在開始測試when not matched子句的陷進(jìn)之前,使用以下腳本創(chuàng)建示例數(shù)據(jù):

大數(shù)據(jù)培訓(xùn),云培訓(xùn),數(shù)據(jù)挖掘培訓(xùn),云計(jì)算培訓(xùn),高端軟件開發(fā)培訓(xùn),項(xiàng)目經(jīng)理培訓(xùn) View Code

一,在on子句中過濾源表

1,在Merge的On子句中,使用額外的篩選條件(s.Code>0)對SourceTable進(jìn)行過濾

對源表進(jìn)行過濾,初衷是為了將SourceTable中Code>0的數(shù)據(jù)作為數(shù)據(jù)源同步到TargetTable,但是,在Merge命令的On