Merge的山寨版“联机帮助”

IF NOT OBJECT_ID('Demo_AllProducts') IS NULL 

DROP TABLE Demo_AllProducts

GO 



CREATE TABLE Demo_AllProducts

(

    PKID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,

    DName NVARCHAR(20) NULL,

    DCode NVARCHAR(20) NULL,

    DDate DATETIME NULL

)

GO  



INSERT INTO Demo_AllProducts

(DName,DCode,DDate)

VALUES

('DemoA','AAA',GETDATE()),

('DemoB','BBB',GETDATE()),

('DemoC','CCC',GETDATE()),

('DemoD','DDD',GETDATE()),

('DemoE','EEE',GETDATE())



SELECT * FROM demo_allproducts



IF NOT OBJECT_ID('Demo_Shop1_product') IS NULL 

DROP TABLE Demo_Shop1_product



CREATE TABLE Demo_Shop1_product

(

    PKID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,

    DName NVARCHAR(20) NULL,

    DCode NVARCHAR(20) NULL,

    DDate DATETIME NULL    

)

GO 



INSERT INTO Demo_Shop1_product

VALUES

('DemoA','AAA',GETDATE()),

('DemoB','CCC',GETDATE()),

('DemoF','FFF',GETDATE())



SELECT * FROM Demo_Shop1_product dsp



--确定目标表

MERGE INTO Demo_AllProducts p 

--查找编码相同的产品

USING Demo_Shop1_product s ON p.DCode=s.DCode

--如果编码相同,名称不同,更新目标表【Demo_AllProducts】名称

WHEN matched AND p.DName<>s.DName THEN UPDATE SET p.DName =s.DName

--如果目标表不存在则插入

WHEN NOT matched BY TARGET THEN INSERT(dname,dcode,ddate) VALUES(s.DName,s.DCode,s.DDate)

--如果目标表数据,子表不存在,删除目标表记录

WHEN NOT matched BY source THEN DELETE ;


土豆的 merge 帮助文档,比联机帮助牛b,哈哈

你可能感兴趣的:(merge)