Oracle游标和DML以及管理事务

select * from dept;在这里插入图片描述
select * from t_emp;在这里插入图片描述
select * from emp;在这里插入图片描述
–1 ,复习DML语句,查询各部门的平均工资,从高到低排序,使用pl/sql输出在控制台
select de.dname, avg(sal) as 平均工资
from dept de, emp e
where de.deptno = e.deptno
group by de.dname;

–2 ,使用PL/SQL写循环,插入10条记录到t_emp表,主键使用随机数.
–因为随机数可能生成的数字相同,所以这里要判断,如果插入的主键已经存在,那么另外再生成一个主键.
–生成随机数代码
–SELECT DBMS_RANDOM.RANDOM FROM DUAL; --随机数
–select trunc(dbms_random.value(0,100)) from dual --0-100范围内的随机数
select * from t_emp
declare
v_id number(10);
v_num number(10):=1; – 给循环赋值
v_count number(10);
begin
loop
exit when v_num>10;
SELECT trunc(dbms_random.value(1,1000)) into v_id FROM DUAL;–得到随机数

select count(*) into v_count from t_emp where e_id = v_id;
if(v_count=0) then--如果id不存在  
  insert into t_emp values(v_id,'新建用户','男',sysdate);
  dbms_output.put_line (1);
  v_num :=v_num+1;--改变循环变量
end if;

end loop;
commit;
end;

–修改emp表中的ID为7369的记录,修改姓名为:张三,然后返回该记录的其他所有信息.并打印出来.
declare
v_deptno number(4);
v_id emp.job%type;
v_name emp.ename%type;
v_sex emp.mgr%type;
v_bir emp.hiredate%type;
begin
v_deptno := 7369 ;
–for v_emp in 1…1
–loop
–dbms_output.put_line(v_emp.ename||’ ‘||v_emp.sal);
update emp t set t.ename=‘张三’ where t.empno=v_deptno
return t.ename,t.job,t.mgr,t.hiredate into v_name,v_id,v_sex,v_bir;
dbms_output.put_line(‘名称为:’||v_name||’ 工作是:’||v_id||’ 性别是:’||v_sex||’ 生日是:’||v_bir);
–end loop ;
commit ;
end ;

–4 , 找出emp表中工资在3000以下的,+300 ,
–3000-5000的+200,
–5000以上的-100.
–使用for游标.
–使用commit;
declare
v_money emp.sal%type;
v_name emp.ename%type;
v_sal emp.sal%type;
begin
for v_emp in (select * from emp) loop
if (v_emp.sal < 3000) then
v_money := 300;
elsif (v_emp.sal >= 3000 and v_emp.sal < 5000) then
v_money := 200;
elsif (v_emp.sal > 5000) then
v_money := -100;
end if;
update emp
set sal = sal + v_money
where empno = v_emp.empno return ename, sal into v_name, v_sal;

dbms_output.put_line(v_name || '    ' || v_sal || '  原工资为:' ||
                     v_emp.sal);

end loop;
commit;
exception
when others then
dbms_output.put_line(sqlerrm);
end;

–5 ,新建一个t_emp_1表,结构和emp表一致,将emp表中工资大于5000的记录加入到t_emp_1表中.
–建立一个和emp一模一样的表,但是不复制数据,只建立表结构.使用如下语句:
–create table t_emp_1 as select * from emp where 1=2 ;
create table t_emp_1 as select * from emp where sal>5000 ;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值