【问题标题】:Old value and new value of record after update更新后记录的旧值和新值
【发布时间】:2020-02-09 16:55:18
【问题描述】:

我需要创建存储过程来找出更新记录的旧值和新值。 它应该包括用于在运行时查找列名的动态查询。

我为此使用 oracle 12C。

create table student (    
    id number(6) primary key,
    name varchar2(50),
    city varchar2(50),
    address varchar2(100),
    createdDateTime date,
    updatedDatetime date
);

insert into student values(1,'abc1','abc1','abc1','09-Jan-20','12-Jan-20');
insert into student values(2,'pqr','pqr','pqr','09-Jan-20',null);

学生桌-

ID      Name    City     Address    Create_time UpdatedTime
1       abc1    abc1     abc1       09-Jan-20   12-Jan-20
2       pqr     pqr      pqr        09-Jan-20   null

create table studentHistory (
    id number(6) ,
    name varchar2(50),
    city varchar2(50),
    address varchar2(100),
    DatetimeCreated date
);

insert into StudentHistory values(1,null,'abc',null,'10-Jan-20');
insert into StudentHistory values(1,'abc',null,null,'11-Jan-20');
insert into StudentHistory values(1,null,null,'abc','12-Jan-20');

学生履历表-

ID  Name    City        Address DatetimeCreated
1   null    abc          null     10-Jan-20
1   abc     null         null     11-Jan-20
1   null    null         abc      12-Jan-20

需要的输出-->

Id  ColumnName Old Value New Value Updatetime
1   City        abc         abc1    '10-01-20'
1   name        abc         abc1    '11-01-20'
1   City        abc         abc1    '12-01-20'

【问题讨论】:

  • “我需要创建存储过程...” - 不,您需要创建一个触发器,它们用于此类目的。互联网上有无数个例子,做一些搜索,写一些代码。如果您无法使其正常工作,请回来 - 如果是这样,请编辑您的问题并发布您编写的代码以及您遇到的错误。
  • 您应该将更新的旧值添加到历史记录表中。现在没有机会获得 UPDATE 的旧值,除非它是最后一个值。然后你只需要一个SELECT 来获取旧值。

标签: sql oracle plsql


【解决方案1】:

我同意@stickybit。填充您的历史记录表确实是起点。您应该像@Littlefoot 提到的那样创建一个触发器来更新/插入您的历史记录表,可能使用合并https://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_9016.htm#SQLRF01606

但是我只是根据您提供的数据尝试了一些东西,不要认为这就是您要查找的内容,但仍将其发布在此处,因为它可能会在将来对其他人有所帮助:

with name_cte
as
(
select 
a.id,
a.name as new_value,
b.name as old_value,
b.datetimecreated,
'name' as column_name
from student a
join studenthistory b
on a.id=b.id
and b.name is not null
)
,city_cte
as
(
select 
a.id,
a.city as new_value,
b.city as old_value,
b.datetimecreated,
'city' as column_name
from student a
join studenthistory b
on a.id=b.id
and b.city is not null
)
,address_cte
as
(
select 
a.id,
a.address as new_value,
b.address as old_value,
b.datetimecreated,
'address' as column_name
from student a
join studenthistory b
on a.id=b.id
and b.address is not null
)
select 
a.id,
a.column_name,
a.old_value,
a.new_value,
a.datetimecreated as updatetime
from name_cte a
union all
select
b.id,
b.column_name,
b.old_value,
b.new_value,
b.datetimecreated as updatetime
from city_cte b
union all
select
c.id,
c.column_name,
c.old_value,
c.new_value,
c.datetimecreated as updatetime
from address_cte c

demo

【讨论】:

    猜你喜欢
    • 2018-01-10
    • 2021-04-05
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多