使用MERGE语句同步表
先建好测试环境: USE TEMPDBGOIF OBJECT_ID(T1) IS NOT NULL DROP TABLE T1IF OBJECT_ID(T2) IS NOT NULL DROP TABLE T2GOCREATE TABLE T1(ID1 INT,VAL1 VARCHAR(50))CREATE TABLE T2(ID2 INT,VAL2 VARCHAR(50))GOINSERT INTO T1SELECT 1,A UNION ALLSELECT
先建好测试环境: USE TEMPDB GO IF OBJECT_ID('T1') IS NOT NULL DROP TABLE T1 IF OBJECT_ID('T2') IS NOT NULL DROP TABLE T2 GO CREATE TABLE T1(ID1 INT,VAL1 VARCHAR(50)) CREATE TABLE T2(ID2 INT,VAL2 VARCHAR(50)) GO INSERT INTO T1 SELECT 1,'A' UNION ALL SELECT 2,'B' UNION ALL SELECT 3,'C' 现在我们的目标是让T2表与T1表同步,我直接把完整的MERGE语句帖上来,等下再细说各个部分:
MERGE INTO T2 AS TB_TARGET USING T1 AS TB_SOURCE ON TB_TARGET.ID2=TB_SOURCE.ID1 WHEN NOT MATCHED BY TARGET THEN INSERT(ID2,VAL2) VALUES(ID1,VAL1) WHEN NOT MATCHED BY SOURCE THEN DELETE WHEN MATCHED AND TB_TARGET.VAL2<>TB_SOURCE.VAL1 THEN UPDATE SET TB_TARGET.VAL2=TB_SOURCE.VAL1 OUTPUT $ACTION,ISNULL(DELETED.ID2,INSERTED.ID2) AS ID,DELETED.VAL2,INSERTED.VAL2 ; 看看MERGE语句输出的结果 /* $ACTION ID2 VAL2 VAL2 ---------- ----------- -------------------------------------------------- -------------------------------------------------- INSERT 1 NULL A INSERT 2 NULL B INSERT 3 NULL C */ 再看一下现在T2的内容: SELECT * FROM T2 /* ID2 VAL2 ----------- -------------------------------------------------- 1 A 2 B 3 C */ 可以看到T1的东东已经过去了,也就是说初步的同步完成了。 现在做一些其它的操作,我们分别插入、更新、删除一条数据: UPDATE T1 SET VAL1='D' WHERE ID1=3 DELETE FROM T1 WHERE ID1=2 INSERT INTO T1 SELECT 4,'E' SELECT * FROM T1 /* ID1 VAL1 ----------- -------------------------------------------------- 1 A 4 E 3 D */ 现在各种数据都有了,1没变,2删了,3改了,4是加的。再运行上面那坨MERGE语句: MERGE INTO T2 AS TB_TARGET USING T1 AS TB_SOURCE ON TB_TARGET.ID2=TB_SOURCE.ID1 WHEN NOT MATCHED BY TARGET THEN INSERT(ID2,VAL2) VALUES(ID1,VAL1) WHEN NOT MATCHED BY SOURCE THEN DELETE WHEN MATCHED AND TB_TARGET.VAL2<>TB_SOURCE.VAL1 THEN UPDATE SET TB_TARGET.VAL2=TB_SOURCE.VAL1 OUTPUT $ACTION,ISNULL(DELETED.ID2,INSERTED.ID2) AS ID,DELETED.VAL2,INSERTED.VAL2 ; /* $ACTION ID VAL2 VAL2 ---------- ----------- -------------------------------------------------- -------------------------------------------------- INSERT 4 NULL E DELETE 2 B NULL UPDATE 3 C D */ 看一下T2的数据 SELECT * FROM T2 /* ID2 VAL2 ----------- -------------------------------------------------- 1 A 3 D 4 E */ 可以看到,数据已经完全同步了。看到效果后,我们就可以开始说正文了,我再粘一次MERGE语句,然后一句一句细说 MERGE INTO T2 AS TB_TARGET USING T1 AS TB_SOURCE ON TB_TARGET.ID2=TB_SOURCE.ID1 WHEN NOT MATCHED BY TARGET THEN INSERT(ID2,VAL2) VALUES(ID1,VAL1) WHEN NOT MATCHED BY SOURCE THEN DELETE WHEN MATCHED AND TB_TARGET.VAL2<>TB_SOURCE.VAL1 THEN UPDATE SET TB_TARGET.VAL2=TB_SOURCE.VAL1 OUTPUT $ACTION,ISNULL(DELETED.ID2,INSERTED.ID2) AS ID,DELETED.VAL2,INSERTED.VAL2 ; 1. MERGE INTO T2 AS TB_TARGET 指定要同步的目标表。MERGE是关键字,INTO可有可无,T2是目标表名,AS可有可无,TB_TARGET是表别名。 如果要对目标表加表提示和索引提示,比如WITH(...),加在T2和AS中间就可以了。 2. USING T1 AS TB_SOURCE 指定用来作为同步源的表或其它东东。USING是关键字,T1是原表名或一个子查询,比如一堆JOIN出来的东西用括号括起来。 AS同上,TB_SOURCE是别名。 3. ON TB_TARGET.ID2=TB_SOURCE.ID1 关联条件,没什么好说的,注意这里开始就用到上面定义的别名了。 4. WHEN NOT MATCHED BY TARGET THEN INSERT(ID2,VAL2) VALUES(ID1,VAL1) 这里放到一起说。看到INSERT应该就能猜这段语句的意思是“如果原表有的记录新表没有,就插入”。 NOT MATCHED表示不匹配, BY TARGET表示是新表找不到匹配原表条件(就是上面的ON后写的)的记录, BY TARGET 可以不写,默认就是BY TARGET,但如果要写两个WHEN MATCHED就必须要写,比如上面这个MERGE。 第二三行和普通的插入语句差不多,区别就在于没有目标表名和只能用VALUES不能用SELECT,因为这里都是针对单行的操作。 5. WHEN NOT MATCHED BY SOURCE THEN DELETE 这个就简单了,如果是原表找不到新表的匹配记录,就把新表的删了。需要注意的就是如果要加上这句,上面的NOT MATCHED必须加BY TARGET。 6. WHEN MATCHED AND TB_TARGET.VAL2<>TB_SOURCE.VAL1 THEN UPDATE SET TB_TARGET.VAL2=TB_SOURCE.VAL1 第一行后面的AND部分可以不要,相当于更新的另一个匹配条件,像上面例子中,ID为1的那条数据没有动,但因为能找到匹配记录还是会更新,加上条件就可以避免这种无效操作了。 7. OUTPUT $ACTION,ISNULL(DELETED.ID2,INSERTED.ID2) AS ID,DELETED.VAL2,INSERTED.VAL2 这行可以都去掉,作用就是输出同步的数据,用过触发器的同学对INSERTED和DELETED两个表应该灰常熟悉,分别放的是更新后的值和更新前的值,看看最后一次MERGE输出的信息就能差不多看出门道了,我就不多说了。如果要调试语句的话,可以加上这句,正常的同步就可以去掉了。 8. ; 这个必须有。。。。。 总之,4,5,6,7都是可以去掉的,但4,5,6至少要有一个,这就是MERGE的全部常用语法了。还有一个最后可以加 OPTION查询提示 最后简单对比一下MERGE和原本同样效果的操作的IO对比 MERGE INTO T2 AS TB_TARGET USING T1 AS TB_SOURCE ON TB_TARGET.ID2=TB_SOURCE.ID1 WHEN NOT MATCHED BY TARGET THEN INSERT(ID2,VAL2) VALUES(ID1,VAL1) WHEN NOT MATCHED BY SOURCE THEN DELETE WHEN MATCHED AND TB_TARGET.VAL2<>TB_SOURCE.VAL1 THEN UPDATE SET TB_TARGET.VAL2=TB_SOURCE.VAL1 OUTPUT $ACTION,ISNULL(DELETED.ID2,INSERTED.ID2) AS ID,DELETED.VAL2,INSERTED.VAL2 ; /* 表 'T2'。扫描计数 2,逻辑读取 7 次,物理读取 0 次,预读 0 次,lob 逻辑读取 0 次,lob 物理读取 0 次,lob 预读 0 次。 表 'T1'。扫描计数 2,逻辑读取 4 次,物理读取 0 次,预读 0 次,lob 逻辑读取 0 次,lob 物理读取 0 次,lob 预读 0 次。 */ PRINT '------------------------------------------------------------------------------------' INSERT INTO T2(ID2,VAL2) SELECT ID1,VAL1 FROM T1 WHERE NOT EXISTS( SELECT 1 FROM T2 WHERE T2.ID2=T1.ID1 ) UPDATE T2 SET T2.VAL2=T1.VAL1 FROM T2 INNER JOIN T1 ON T2.ID2=T1.ID1 AND T2.VAL2<>T1.VAL1 DELETE FROM T2 WHERE NOT EXISTS( SELECT 1 FROM T1 WHERE T1.ID1=T2.ID2 ) /* 表 'T2'。扫描计数 1,逻辑读取 4 次,物理读取 0 次,预读 0 次,lob 逻辑读取 0 次,lob 物理读取 0 次,lob 预读 0 次。 表 'Worktable'。扫描计数 1,逻辑读取 5 次,物理读取 0 次,预读 0 次,lob 逻辑读取 0 次,lob 物理读取 0 次,lob 预读 0 次。 表 'T1'。扫描计数 1,逻辑读取 1 次,物理读取 0 次,预读 0 次,lob 逻辑读取 0 次,lob 物理读取 0 次,lob 预读 0 次。 表 'T2'。扫描计数 1,逻辑读取 2 次,物理读取 0 次,预读 0 次,lob 逻辑读取 0 次,lob 物理读取 0 次,lob 预读 0 次。 表 'T1'。扫描计数 1,逻辑读取 4 次,物理读取 0 次,预读 0 次,lob 逻辑读取 0 次,lob 物理读取 0 次,lob 预读 0 次。 表 'T2'。扫描计数 1,逻辑读取 1 次,物理读取 0 次,预读 0 次,lob 逻辑读取 0 次,lob 物理读取 0 次,lob 预读 0 次。 表 'T1'。扫描计数 1,逻辑读取 4 次,物理读取 0 次,预读 0 次,lob 逻辑读取 0 次,lob 物理读取 0 次,lob 预读 0 次。 */

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

When you find that one or more items in your sync folder do not match the error message in Outlook, it may be because you updated or canceled meeting items. In this case, you will see an error message saying that your local version of the data conflicts with the remote copy. This situation usually happens in Outlook desktop application. One or more items in the folder you synced do not match. To resolve the conflict, open the projects and try the operation again. Fix One or more items in synced folders do not match Outlook error In Outlook desktop version, you may encounter issues when local calendar items conflict with the server copy. Fortunately, though, there are some simple ways to help

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

What do you think of furmark? 1. Set the "Run Mode" and "Display Mode" in the main interface, and also adjust the "Test Mode" and click the "Start" button. 2. After waiting for a while, you will see the test results, including various parameters of the graphics card. How is furmark qualified? 1. Use a furmark baking machine and check the results for about half an hour. It basically hovers around 85 degrees, with a peak value of 87 degrees and room temperature of 19 degrees. Large chassis, 5 chassis fan ports, two on the front, two on the top, and one on the rear, but only one fan is installed. All accessories are not overclocked. 2. Under normal circumstances, the normal temperature of the graphics card should be between "30-85℃". 3. Even in summer when the ambient temperature is too high, the normal temperature is "50-85℃

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

Apple rolled out the iOS 17.4 update on Tuesday, bringing a slew of new features and fixes to iPhones. The update includes new emojis, and EU users will also be able to download them from other app stores. In addition, the update also strengthens the control of iPhone security and introduces more "Stolen Device Protection" setting options to provide users with more choices and protection. "iOS17.3 introduces the "Stolen Device Protection" function for the first time, adding extra security to users' sensitive information. When the user is away from home and other familiar places, this function requires the user to enter biometric information for the first time, and after one hour You must enter information again to access and change certain data, such as changing your Apple ID password or turning off stolen device protection.
