Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

SQL Merge Statement Explanantion

$
0
0

Hello Experts,

We have an SQL Stored procedure that updates records in a table based with the results from a view.

UPDATE RD     
	SET     
		RD.ColA = RTL.COLA,RD.COLB = RTL.COLB
	FROM 
		dbo.TAB1 as RD      
	LEFT OUTER JOIN 
		VIEW2
	ON       
		(RD.CID1  = View2.CID)

The OUTER Join syntax was included to ensure that records that do not have matching values from view get updated with NULL Value.

A team member suggested the use of the Merge Syntax

MERGE INTO TABLE AS TARGET
	USING
	(
		SELECT
			COLA, COLB, CID
		FROM VIEW2
	)
	AS SOURCE
	ON SOURCE.CID= TARGET.CID 
	WHEN MATCHED THEN
		UPDATE
		SET
		COLA = SOURCE.COLA,
		COLB= SOURCE.COLB
	WHEN NOT MATCHED BY SOURCE THEN
		UPDATE
		SET
		COLA= NULL,
		COLB= NULL
	;

Which of the two approaches is best? The execution times are pretty much the same? Can somebody explain the advantage or disadvantage of using either approach?


Regards, Dinesh


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>