对oracle当中子查询建表,merge操作,创建,修改,删除约束,创建使用触发器的复习练习(二)...

本文详细介绍了如何在数据库中修改字段长度、批量插入数据、使用子查询建立备份表、合并数据并设置触发器自动更新备份表。通过实例演示了在数据库操作中使用匿名程序块、循环、合并语句及触发器的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

--修改字段的长度
alter table productinfo_bak
modify productName varchar2(20);

--使用匿名程序块,在里面使用loop循环给表出入9条数据
declare
begin
  for i in 1 .. 9 loop
    insert into productinfo
      (productid, productname, productprice, productaddress)
    values
      ('GD01001000'||i,'LG手机'||i,'手机价格'||i,'西安市南山区地址'||i);
    commit;
  end loop;
  dbms_output.put_line('总共插入了'||sql%rowcount||'条记录.');
end;

--使用子查询建立表productinfo_bak
create table productinfo_bak as  select * from productinfo  where 1<>1;

--使用merge语句给表productinfo_bak里面插入一条p.productid ='GD010010001'的记录
merge into productinfo_bak p_bak
using productinfo p
on (p_bak.productId = p.productId)
when not matched then
  insert
    (p_bak.productid,
     p_bak.productname,
     p_bak.productprice,
     p_bak.productaddress)
  values
    (p.productid, p.productname, p.productprice, p.productaddress) where p.productid = 'GD010010001';
  
--创建触发器,行级触发器(for each row),在更新productinfo表的时候触发事件
create or replace trigger tr_auto_update_productinfo
after update on productinfo for each row
begin
  update productinfo_bak p_bak set 
  p_bak.productid    = :new.productid,    p_bak.productname   =  :new.productname, 
  p_bak.productprice = :new.productprice, p_bak.productaddress = :new.productaddress
  where  p_bak.productid = :old.productid;/** 该where条件非常重要,意在只更新产品推荐表里有的数据**/
  dbms_output.put_line('你在更新产品信息的时候,触发器自动更新了产品备份表里面的信息!');
exception
  when others then
    dbms_output.put_line(sqlcode ||'  ,' ||sqlerrm);
end;

select * from productinfo;
select * from productinfo_bak;
update productinfo p set p.productname = '金鹏1' where p.productid = 'GD010010001';
select * from productinfo_bak;
--在本例子中我犯了一个致命的错误就是在触发器的定义当中使用了事物控制语句

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值