创建表:
create table tuser(
id number(11) not null,
name varchar2(20) not null,
password varchar2(20),
birthday date,
constraint tuser_pk primary key (id)
);
创建序列:
create sequence increase_seq increment by 1 start with 1 nomaxvalue nocycle cache 10;
创建trigger:
create or replace trigger tuser_trigger
before insert on tuser for each row
begin
select increase_seq.nextval into :new.id from dual; 关于dual表可以参看:http://wujay.iyunv.com/blog/1836847
end;
/
根据使用的工具,可能需要增加“/”来执行PL/SQL块。
测试:
insert into tuser(name,password,birthday) values('wujay','123456',null);
commit;
select * from tuser;
ID NAME PASSWORD BIRTHDAY
---------- -------------------- -------------------- --------------
1 wujay 123456
修改表:
alter table tuser rename column id to pk_tuser;
修改trigger:
--添加数据
--所有字段都插入数据
insert into student values ('a001', '张三', '男', '01-5 月-05', 10);
--oracle中默认的日期格式‘dd-mon-yy’ dd 天 mon 月份 yy 2位的年 ‘09-6 月-99’ 1999年6月9日
--修改日期的默认格式(临时修改,数据库重启后仍为默认;如要修改需要修改注册表)
alter session set nls_date_format ='yyyy-mm-dd';
--修改后,可以用我们熟悉的格式添加日期类型:
insert into student values ('a002', 'mike', '男', '1905-05-06', 10);
--插入部分字段
insert into student(xh, xm, sex) values ('a003', 'john', '女');
--插入空值
insert into student(xh, xm, sex, birthday) values ('a004', 'martin', '男', null);
--问题来了,如果你要查询student表里birthday为null的记录,怎么写sql呢?
--错误写法:select * from student where birthday = null;
--正确写法:select * from student where birthday is null;
--如果要查询birthday不为null,则应该这样写:
select * from student where birthday is not null;
--修改数据
--修改一个字段
update student set sex = '女' where xh = 'a001';
--修改多个字段
update student set sex = '男', birthday = '1984-04-01' where xh = 'a001';
--修改含有null值的数据
不要用 = null 而是用 is null;
select * from student where birthday is null;
--删除数据
delete from student; --删除所有记录,表结构还在,写日志,可以恢复的,速度慢。
--delete的数据可以恢复。
savepoint a; --创建保存点
delete from student;
rollback to a; --恢复到保存点
一个有经验的dba,在确保完成无误的情况下要定期创建还原点。
drop table student; --删除表的结构和数据;
delete from student where xh = 'a001'; --删除一条记录;
truncate table student; --删除表中的所有记录,表结构还在,不写日志,无法找回删除的记录,速度快。