在同一查询中使用UPDATE和INSERT

时间:2013-04-13 12:17:01

标签: sql db2

我可以在同一查询中进行插入和更新吗?

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 |   

获取行

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

插入新行

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

更新旧行

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

是否可以在一个查询中实现此目的(不使用存储过程或触发器等)

谢谢。

1 个答案:

答案 0 :(得分:0)

你有两个选择:

  1. 使用触发器(在谷歌上查看“DB2 9.5 Cookbook”,第333页。以及使用具有历史数据的触发器的示例)

  2. 升级到DB2 Version 10并使用系统时间通过时间旅行查询查询历史数据。

相关问题