0

Can I do an insert and update in same query?

BEFORE:

MemberID |   SubsID |   StartDate  |  EndDate
------------------------------------------------
1001     |   10     |   2012-12-21 |  2012-12-31 
2002     |   10     |   2012-12-22 |   

AFTER:

MemberID |   SubsID |   StartDate  |  EndDate
------------------------------------------------
1001     |   10     |   2012-12-21 |  2012-12-31 
2002     |   10     |   2012-12-22 |  2012-04-13 
2002     |   10     |   2012-04-13 |   

Get the rows:

select * from MemberSubs 
where SubsID = 10 and EndDate is null;

Insert new rows:

insert into 
  MemberSubs(MemberID, SubsID, Price, StartDate)
select 
  MemberID, SubsID, Price, Current Date 
from 
  MemberSubs 
where 
  SubsID = 10
  and
  EndDate is null

Update the old rows:

update MemberSubs 
set 
  EndDate = current date
where 
  SubsID = 10
  and
  EndDate is null
  and
  StartDate < Current Date

Is it possible to achieve this in one query (without using stored procedures or trigger etc)

Thank you.

MrSimpleMind
  • 7,890
  • 3
  • 40
  • 45
  • Duplicate as above - you're looking for the `MERGE` statement. – Yuck Apr 13 '13 at 12:40
  • Thanks for the thread about MERGE statement, but can someone please give a hint on how to achieve this using MERGE ? How would my MERGE query look like? I have never used MERGE. – MrSimpleMind Apr 14 '13 at 10:49
  • I dont understand how MERGE could solve this? Are you sure this is can be solved by using MERGE statement ? I have read ibm manuals, and other pdfs etc. I can not figure out how to do update and insert in same query, it is not "update or insert" it is "update and insert" (or "insert and update" no matter which query I start with). – MrSimpleMind Apr 15 '13 at 11:45
  • https://stackoverflow.com/a/16032501/1223532 – MrSimpleMind Aug 23 '18 at 11:04

1 Answers1

0

you have 2 options:

  1. use triggers (look after "DB2 9.5 Cookbook " on google, at page 333. theres a sample of using triggers with history data)

  2. upgrade to DB2 Version 10 and use system time to query history data with time travel queries.

Seb.B.
  • 151
  • 1
  • 3