Merge tables(add, update and delete records from d

2019-08-30 05:06发布

问题:

I have three tables tb1,tb2 and tbTotal. They have the same schemas. The tables have three columns, MetricID, Descr and EntryDE.

What I want is to merge tb1 with tbTotal. I have done this and it works fines. My stored procedure is:

CREATE PROCEDURE [dbo].[Admin_Fill] 
-- Add the parameters for the stored procedure here
@MetricId INT,
@Descr VARCHAR(100),
@EntryDE VARCHAR(20)
 AS

 BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
--SET IDENTITY_INSERT dbo.tbTotal ON
-- Insert statements for procedure here
;WITH cte AS (SELECT MetricId=@MetricId,Descr=@Descr,EntryDE=@EntryDE)
 MERGE tbTotal d
 USING cte s
 ON s.EntryDE = d.EntryDE
 AND s.MetricId=d.MetricId
 WHEN matched THEN UPDATE
 set MetricId=s.MetricId,
     Descr=s.Descr,
     EntryDE=s.EntryDE
 WHEN not matched BY TARGET THEN
 INSERT(MetricId,Descr,EntryDE)
 VALUES (s.MetricId,s.Descr,s.EntryDE);
 END

My C# code:

        foreach (DataRow row in dt.Rows) // pass datatable dt1
        {
            MetricId = Convert.ToInt32(row["MetricId"]);
            Descr = row["Descr"].ToString();
            EntryDE = row["EntryDE"].ToString();
            parameters.Add("@MetricId", MetricId);
            parameters.Add("@Descr", Descr);
            parameters.Add("@EntryDE", EntryDE);
            dbaccess.ExecuteNonQuery(strStoredProcedure, parameters); //cmd.ExecuteNonQuery(); 
            parameters.Clear();
        }

Also I want to remove all records in dt2 from dtTotal. I am not sure how to modify the stored procedure.

Thanks for help.

回答1:

If i have understood what you are trying to do correctly, then this is potentially how I would prefer to implement the solution.

I would pass the 2 datatables as TABLE variables to an SP - similar to below and then use JOINs to both UPDATE and DELETE as required using SET operations - thus affecting multiple rows in one query and avoid looping through each row separately.

As mentioned by AdaTheDev in the related answer, you will end up creating a "TABLE" type but there is no drawback to having one extra type and this solution will scale a lot better than a looping approach would.

DISCLAIMER :- Code below may not be syntactically correct but i hope you get the picture of what I am proposing.

CREATE TYPE TableType AS TABLE
(
 MetricId INT, 
 Descr VARCHAR(300) --or whatever length is appropriate, 
 EntryDE INT
);
GO

CREATE PROCEDURE [dbo].[Admin_Fill] 
  @RowsForUpdate TableType READONLY,
  @RowsForDelete TableType READONLY
AS
BEGIN

  -- Update all the Descriptions for all the rows
  UPDATE
    t
  SET
    t.Descr = u.Descr
  FROM
    tbTotal t 
  INNER JOIN @RowsForUpdate u
    ON t.EntryDE = u.EntryDE AND t.MetricId = u.MetricId

  -- Delete the rows to be deleted
  DELETE t 
  FROM tbTotal t
  INNER JOIN @RowsForDelete d
    ON t.EntryDE = u.EntryDE AND t.MetricId = u.MetricId

END