Answers collected from the below site.Please refer to the site for details.
Using MERGE in SQL Server to insert, update and delete at the same time
MERGE <target_table> [AS TARGET]
USING <table_source> [AS SOURCE]
ON <search_condition>
[WHEN MATCHED
THEN <merge_matched> ]
[WHEN NOT MATCHED [BY TARGET]
THEN <merge_not_matched> ]
[WHEN NOT MATCHED BY SOURCE
THEN <merge_ matched> ];
The MERGE statement basically merges data from a source result set to a target table based on a condition that you specify and if the data from the source already exists in the target or not.
-----------------------------------------------------------------------
Source Video: SQL Server 2008 MERGE
--MERGE Statement
MERGE INTO dbo.tbl1 tbl ---target
USING (Select 'Seven' as Col2) src --source
ON (tbl.col2 = src.col2)
WHEN MATCH THEN
UPDATE SET COL2 = 'Eight'
WHEN TARGET NOT MATCHED THEN
INSERT (Col2) Values ('Seven');
Go
Select * from dbo.tbl1;
Go
-------------------------------------------------------------------------
USE DemoDb
Go
Insert into dbo.tbl (col2) VALUES ('One');
Go
Select * from dbo.tbl1;
Go
--If-else Statement
IF EXISTS(SELECT * from dbo.tbl1 WHERE col2 = 'FIVE')
UPDATE dbo.tbl1 Set Col2 = 'Six' WHERE Col2= 'FIVE';
ELSE
INSERT INTO dbo.tbl1 (col2) VALUES('Five);
Go
Select * from dbo.tbl1 ;
--Drop Table
IF EXISTS(......
DROP TABLE [dbo].[tbl1];
Go
--Create table
CREATE TABLE [dbo].[tbl1] ( [Col1] [int] IDENTITY(1,1) NOT NULL, [Col2] [Varchar] (50) NOT NULL,
CONSTRAINT [PK_tbl1] PRIMARY KEY CLUSTERED [COL1] ASC
)
GO
Col1. Col2.
1 One
2 Two
3 Three
4 Four
--MERGE Statement
MERGE INTO dbo.tbl1 tbl ---target
USING (Select 'Seven' as Col2) src --source
ON (tbl.col2 = src.col2)
WHEN MATCH THEN
UPDATE SET COL2 = 'Eight'
WHEN TARGET NOT MATCHED THEN
INSERT (Col2) Values ('Seven');
Go
Select * from dbo.tbl1;
Go
No comments:
Post a Comment