XML Data Insert,Update with MERGE in sql server

XML Data Insert,Update with MERGE in sql server

First of all you have to select XML data into a temptable, that will use as SOURCE table in merger statement.

SELECT
		ISNULL(x.v.value('Id[1]', 'int'), '') AS Id,
		ISNULL(x.v.value('Name[1]', 'bit'), '') AS Name,
		ISNULL(x.v.value('Address[1]', 'bit'), '') AS Address,
		ISNULL(x.v.value('Status[1]', 'nvarchar(max)'), '') AS Status,
		ISNULL(x.v.value('MoNumber[1]', 'nvarchar(max)'), '') AS MoNumber,
		ISNULL(x.v.value('Location[1]', 'nvarchar(max)'), '') AS Location,
		ISNULL(x.v.value('Email[1]', 'nvarchar(max)'), '') AS Email
		INTO #TempData
	FROM @XMLData.nodes('/ArrayOfEmployeeAccessModel/EmployeeModel') x (v);

And then you can user MERGER Statement to insert or update according to condition.

MERGE tbl_UpdatedEmployee AS TARGET
		USING #TempData AS SOURCE 
		ON (
		TARGET.PKId = SOURCE.Id 
		) 
		WHEN MATCHED  THEN 
		UPDATE 
		SET TARGET.Name = SOURCE.Name,
                    TARGET.Address= SOURCE.Address,
			
		WHEN NOT MATCHED BY TARGET THEN 
		INSERT (Name,Address,Status,MoNumber,Location,Email) 
		VALUES (SOURCE.Name,SOURCE.Address,SOURCE.Status,SOURCE.MoNumber,SOURCE.Location,SOURCE.Email)
		
Also if you want to get INSERTED or UPDATED rows or data than you can get as resultset, but for this first of all you have to declare a table variable on top then you can get output as table and return as resultset.
DECLARE @output TABLE (Id int,Email VARCHAR(50),Password NVARCHAR(10))
 In Above statement you can declare the columns name which you want to take as output columns, above defined a table variable.
 And now you have to add a statement at the last of merge statement, and you have to put ; (semicolon) at last of OUTPUT data statement.

MERGE tbl_UpdatedEmployee AS TARGET
		USING #TempData AS SOURCE 
		ON (
		TARGET.PKId = SOURCE.Id 
		) 
		WHEN MATCHED  THEN 
		UPDATE 
		SET TARGET.Name = SOURCE.Name,
                    TARGET.Address= SOURCE.Address,
			
		WHEN NOT MATCHED BY TARGET THEN 
		INSERT (Name,Address,Status,MoNumber,Location,Email) 
		VALUES (SOURCE.Name,SOURCE.Address,SOURCE.Status,SOURCE.MoNumber,SOURCE.Location,SOURCE.Email)

               OUTPUT INSERTED.Id,INSERTED.Address,INSERTED.Status INTO @output;
And now you can select your table variable as resultset.
SELECT * FROM @output

For More Detail about MERGE Visit Microsoft MSDN Weblink
Link