Simplifying SQL computing for dynamic merge

Source: Internet
Author: User
Tags mssql

MSSQL. Databases such as Oracle support the Merge Statement Update table. However, the table structure is unknown because of the lack of collection class data. Using stored procedures to get a table structure and then dynamically spell out SQL is cumbersome, with dozens of lines of code, and the same reason that it is not easy to implement in high-level languages such as Java. and using stored procedures or Java programs requires code to be built into the database or application, and update management is cumbersome. With the help of the collector, the code can be placed outside the database and application, without affecting the structure of the database and application, and is easy to maintain.

The reference source and target represent two tables with the same structure but different data, requiring the primary key as the standard to update the target with source, such as the primary keys for Table1 and table2 are both A and B, data such as the following:


with table2 Update table1 when the MERGE statements should be such as the following:

MERGE into table1 as T   USING table2 as S on   T.A=S.A and t.b=s.b when matched then   UPDATE SET t.c=s.c,t . D=S.D when isn't   matched then   INSERT VALUES (S.A,S.B,S.C,S.D)
after the updatetable1should be for example the following:

The Collector code:


A1,A2: The primary key of the table source read from the system table is stored in the variable PKS, and the result is set ["A", "B"]. The methods for obtaining primary keys are different for various databases. Here, take MSSQL as an example.

A3,A4: read out the full field of source, the columns evaluates to ["A", "B", "C", "D"].

A5: Dynamically generate the merge statement. PKs. (...) is a looping function that calculates the members of the collection (which contains the result set) in turn. Used in calculations ~ Reference loop variables. Use the # Reference loop count.

A6: Run the merge statement.


Simplifying SQL computing for dynamic merge

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.