Link to home
Start Free TrialLog in
Avatar of j_heck

asked on

MS SQL Update an Existing Row and Insert the New Row

I have two tables, TableA & TableB, TableA is the production table and TableB is a working table.  I need to Insert the rows in TableB that do not exist in TableA and update the rows in TableA that are in TableB, which I can do using the MERGE command.  The problem I am running into is trying to Insert the row in TableB as a new row if it already exist in TableA.  The MERGE command does not allow the insertion of a row on the WHEN MATCHED in the MERGE command.  By updating the MATCHED row in TableA first before inserting the new row in TableB will keep the data unique.

I know I can do this by reading the table multiple times, once to do the UPDATE and then again to do the INSERT command.  I would like to skip the double read by using the MERGE command if possible.  If it cant be done then I will just run two pieces of code; one for UPDATE and one for INSERT

Any suggestions?

Avatar of chaau
Flag of Australia image

With MERGE statements you can have multiple WHEN MATCHED conditions. See here the last example D. There they demonstrated multiple conditions, like this:

    WHEN MATCHED AND pi.Quantity - src.OrderQty >= 0 
        THEN UPDATE SET pi.Quantity = pi.Quantity - src.OrderQty
    WHEN MATCHED AND pi.Quantity - src.OrderQty <= 0 

Open in new window

In your case, you can specify a loose condition in your ON clause, and then use some additional WHEN MATCHED statement to specify some additional rules.

It would help if you could provide some sample data with table structures ( preferable)
Avatar of j_heck


Chaau, here is some sample table layout and data below.  TableA is a table the user builds for import purposes and TableB is the production data.  In this example,  Since StockNumber 1234 already exist in TableB what needs to happen is 1) the row in TableB needs to have the EndDate changed to 2013-09-14 (TableA.BeginDate -1);  2)  the row with the StockNumber 1234 in TableA needs to be added to TableB.  the other two rows in TableA, StockNumber's 4567 & 8765, need to be added to TableB.  

The problem I have is when the StockNumber in TableA already exist in TableB, as in example 1, the MERGE needs to do an UPDATE and then an INSERT.  Does this clear it up at all?

StockNumber INT
BeginDate DATE
EndDate DATE
Price DECIMAL(10,2)

StockNumber INT
BeginDate DATE
EndDate DATE
Price DECIMAL(10,2)

TableA Data
1234    2013-09-15    2013-09-30    4.65
4567    2013-09-01    2013-09-30    6.43
8765    2013-09-15    2013-09-30    8.29

TableB Data
1234    2013-09-01    2013-09-30    5.65
2938    2013-09-01    2013-09-30   12.43
Avatar of chaau
Flag of Australia image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of j_heck


chaau,  I expanded the example you created to see if I could get it to work and I am getting an error and having trouble figuring out where I am going wrong.  Here is the error:

Column name or number of supplied values does not match table definition.

Here is my expanded script. I did add to the ON part of the MERGE statement because I realized that there can be the same stock number multiple times but I want to make changes to the one that matches the CurrentBeginDate and CurrentEndDate:

INSERT INTO SpecialScanBackAll
MERGE SpecialScanBackAll AS T
USING SpecialScanBackImport AS S
ON S.UPC = T.StockNumber
      and T.BeginDate = S.CurrentBeginDate
      and T.EndDate = S.CurrentEndDate
  UPDATE SET T.BeginDate = S.NewBeginDate, T.EndDate = S.NewEndDate, T.ScanBackAmount = S.NewScanBack
  INSERT (storeid, storeid3, [StockNumber], pack, ScanBackAmount, PerMove, [BeginDate], [EndDate], AddDate,
                  GroupType, VendorNbr, Zone, MfgId, RTC)
  VALUES (0, 0, S.[StockNumber], 1, S.NewScanBack, 1, S.[NewBeginDate], S.[NewEndDate], GetDate(),
                  'Corporate', 0, 0, BillMfgId, 1)
OUTPUT deleted.StoreId, deleted.StoreId3, deleted.StockNumber, deleted.Pack, deleted.ScanBackAmount,
            deleted.BeginDate, dateadd(d, -1, inserted.BeginDate) As EndDate, deleted.AddDate, deleted.GroupType,
            deleted.VendorNbr, deleted.Zone, deleted.MfgId, deleted.RTC
) AS D

Here are the two file layouts:
Source Table:
      [StockNumber] [decimal](20, 0) NULL,
      [CurrentScanBack] [decimal](10, 3) NULL,
      [NewScanback] [decimal](10, 3) NULL,
      [CurrentBeginDate] [date] NULL,
      [CurrentEndDate] [date] NULL,
      [NewBeginDate] [date] NULL,
      [NewEndDate] [date] NULL,
      [WhoToBill] [nvarchar](50) NULL,
      [BillMfgId] [int] NULL

Target table:
      [StoreId] [int] NULL,
      [StoreId3] [int] NULL,
      [StockNumber] [decimal](20, 0) NULL,
      [Pack] [smallint] NULL,
      [ScanBackAmount] [decimal](10, 3) NULL,
      [PerMove] [smallint] NULL,
      [BeginDate] [date] NULL,
      [EndDate] [date] NULL,
      [AddDate] [date] NULL,
      [GroupType] [nchar](25) NULL,
      [VendorNbr] [int] NULL,
      [Zone] [int] NULL,
      [MfgId] [int] NULL,
      [RTC] [bit] NULL
You forgot to add deleted.permove after deleted.ScanBackAmount in the output clause. Your target table has 14 columns but the output clause has only 13