I want to replace a table “Met” in my sql server database with a new datatable from an application.
My basic idea to loop each row in the new table and compare the existing table.
I used a stored procedure, but it only having “insert “and “update” function. Do I need delete the old table first?
Thanks
For each row, I want to loop the following stored procedure.
;WITH CTE AS (SELECT skey=@skey,ProbMetID=@ProbMetID,Interval=@Interval,Counts=@Counts)
MERGE Met AS TARGET
USING CTE SOURCE
ON SOURCE.skey = TARGET.skey
WHEN MATCHED THEN
UPDATE
SET ProbMetID = SOURCE.ProbMetID,
Interval = SOURCE.Interval,
Counts = SOURCE.Counts,
WHERE skey = @skey
WHEN NOT MATCHED THEN
INSERT INTO Met(skey,ProbMetID,Interval,Counts)
VALUES(@skey,@ProbMetID,@Interval,@Counts);
The MERGE statement does include a DELETE function. Check out Pinal Dave’s post on it: http://blog.sqlauthority.com/2008/08/28/sql-server-2008-introduction-to-merge-statement-one-statement-for-insert-update-delete/
I’ve found that the easiest way to do this from the app layer is to insert everything into a temp table, then perform the entire MERGE operation between the temp table and the actual table. The great part is that you can do the entire thing in a single transaction. Plus, you can bulk insert the application table into the temp table for super awesome db speed (TM).