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?

Thanks.
j_heckAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

chaauCommented:
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 
        THEN DELETE

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 (SQLFiddle.com preferable)
0
j_heckAuthor Commented:
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?

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


TableB
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
0
chaauCommented:
Yes, this could be done with a small "OUTPUT" trick. Have a look:

INSERT INTO TableB
SELECT * FROM
(
MERGE TableB AS B
USING TableA AS A
ON A.StockNumber = B.StockNumber
WHEN MATCHED THEN
  UPDATE SET B.BeginDate = A.BeginDate, B.EndDate = A.EndDate, B.Price = A.Price
WHEN NOT MATCHED BY TARGET THEN
  INSERT ([StockNumber], [BeginDate], [EndDate], [Price])
  VALUES (A.[StockNumber], A.[BeginDate], A.[EndDate], A.[Price])
OUTPUT deleted.StockNumber, deleted.BeginDate, dateadd(d, -1, inserted.BeginDate) As EndDate, deleted.Price
) AS D
WHERE D.StockNumber IS NOT NULL;

Open in new window


Result:
| STOCKNUMBER |  BEGINDATE |    ENDDATE | PRICE |
---------------|---------------|---------------|----------|--
|        1234 | 2013-09-15 | 2013-09-30 |  4.65 |
|        1234 | 2013-09-01 | 2013-09-14 |  5.65 |
|        2938 | 2013-09-01 | 2013-09-30 | 12.43 |
|        4567 | 2013-09-01 | 2013-09-30 |  6.43 |
|        8765 | 2013-09-15 | 2013-09-30 |  8.29 |

Open in new window


SQLFiddle
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
j_heckAuthor Commented:
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
SELECT * FROM
(
MERGE SpecialScanBackAll AS T
USING SpecialScanBackImport AS S
ON S.UPC = T.StockNumber
      and T.BeginDate = S.CurrentBeginDate
      and T.EndDate = S.CurrentEndDate
WHEN MATCHED THEN
  UPDATE SET T.BeginDate = S.NewBeginDate, T.EndDate = S.NewEndDate, T.ScanBackAmount = S.NewScanBack
WHEN NOT MATCHED BY TARGET THEN
  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
WHERE D.StockNumber IS NOT NULL;

Here are the two file layouts:
Source Table:
[dbo].[SpecialScanBackImport](
      [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:
[dbo].[SpecialScanBackAll](
      [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
0
chaauCommented:
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
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.