TSQL Merge on clause and when clause understanding

Source: Internet
Author: User

The ON clause of the Merge specifies that the match condition,when clause specifies the filter condition, which is well understood if the source table and Targe table match, and if not, you must understand the mismatched condition in depth, otherwise it is prone to error.

1. Create Sample Data

Create TableDbo.dt_source (IDint, Codeint)GoCreate TableDbo.dt_target (IDint, Codeint)GoInsert  intoDbo.dt_source (Id,code)Values(1,1),(2,1),(3,2),(4,2),(5,0)GOInsert  intodbo.dt_target (Id,code)Values(1,1),(6,4)GO

2, the SourceTable is filtered using the additional filter criteria (S.CODE>0) in the merge's on clause. The intention was to synchronize the data code>0 in SourceTable to targettable as a data source, but in the ON clause of the merge, S.code>0 was just a match condition;

The not matched clause refers to the t.id=s.id and s.id>0 that are not satisfied, and the logical result is: T.id<>s.id or s.id<=0, which dbo.dt_source in id<=0 satisfies not Matched semantics, so it is inserted into the dbo.dt_target.

; Merge Dbo.dt_target astusing Dbo.dt_source ass onT.id=S.id andS.code>0 whenmatched Then UpdateSetT.code=S.code when  notmatched Then Insert(Id,code)Values(S.id,s.code);

View Targettable,code=0 data is inserted into the Targetable table with the following data:

When synchronizing data with the merge clause, the SourceTable filter is placed in the When clause, and if the filter condition is not added to the When clause, the entire sourcetable is synchronized.

; Merge Dbo.dt_target astusing Dbo.dt_source ass onT.id=S.id
whenmatched and s.code>0 Then UpdateSetT.code=S.code when notMatched andS.code>0 Then Insert(Id,code)Values(S.id,s.code);

TSQL Merge on clause and when clause understanding

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.