1. 序列号
- 序列生成器在多用户环境下产生唯一的数字序列
- 独立于表的对象,由Oracle自动维护
- 同一个序列号可供多个用户(表)使用且相互独立
1.1 序列号创建与使用
EX:
SQL> create sequence stuseq --创建一个序列号
2 start with 2000
3 increment by 1;
Sequence created
SQL> create table student(student_id number,name varchar2(20),sex char(2),birth_place varchar2(20));
Table created
SQL> desc student;
Name Type Nullable Default Comments
----------- ------------ -------- ------- --------
STUDENT_ID NUMBER Y
NAME VARCHAR2(20) Y
SEX CHAR(2) Y
BIRTH_PLACE VARCHAR2(20) Y
SQL> insert into student values(stuseq.nextval,'TOM','F','Boston');
1 row inserted
SQL> select * from student;
STUDENT_ID NAME SEX BIRTH_PLACE
---------- -------------------- --- --------------------
2001 TOM F Boston
-- ??按理说应该是2000,为开始值
SQL> insert into student values(stuseq.nextval,'TOM2','F','Boston');
1 row inserted
SQL> select * from student;
STUDENT_ID NAME SEX BIRTH_PLACE
---------- -------------------- --- --------------------
2001 TOM F Boston
2002 TOM2 F Boston
2. 事务
其原子性决定一个事务要么不做,要么做完
2.1 COMMIT
- 提交保证数据更改永久有效,其他用户也可看到一致数据
- 修改后未提交,重新登陆将失效,其他用户也看不到相关修改
2.2 ROLLBACK
修改后未提交,回滚可将数据恢复到原始数值
EX:
-- 查询数据
SQL> select sal from emp where empno = 7654;
SAL
---------
1250.00
-- 更新数据
SQL> update emp set sal=1000 where empno=7654;
1 row updated
-- 查询数据已更新
SQL> select sal from emp where empno = 7654;
SAL
---------
1000.00
-- 回滚
SQL> rollback;
Rollback complete
-- 数据已恢复
SQL> select sal from emp where empno = 7654;
SAL
---------
1250.00
2.3 SAVEPOINT
EX:
SQL> declare
2 var_salary number(8,2);
3 begin
4 update emp set sal=1000 where empno=7654;
5 select sal into var_salary from emp where empno=7654;
6 dbms_output.put_line ('the first step salary is :'||var_salary);
7 savepoint a1; #设置保留点a1
8 update emp set sal=10001 where empno=7654;
9 select sal into var_salary from emp where empno=7654;
10 dbms_output.put_line ('the second step salary is :'||var_salary);
11 savepoint a2;#设置保留点a2
12 update emp set sal=10002 where empno=7654;
13 select sal into var_salary from emp where empno=7654;
14 dbms_output.put_line ('the third step salary is :'||var_salary);
15 savepoint a3;#设置保留点a3
16 rollback to a1;#回滚到保留点a1
17 dbms_output.put_line ('the final step salary is :'||var_salary);
18 end;
19 /
the first step salary is :1000
the second step salary is :10001
the third step salary is :10002
the final step salary is :10002
PL/SQL procedure successfully completed
SQL> select sal from emp where empno = 7654;
SAL
---------
1000.00
rollback to a1后,语句块未结束,故事务也未结束,“PL/SQL procedure successfully completed”后查看数据,已修改完成