您的位置:首页 > 数据库 > Oracle

oracle创建表相关

2015-10-10 18:18 302 查看
--创建表
create table person(
id number primary key,
name varchar2(40),
birth date
);
--创建序列
create sequence person_id_seq
increment by 1
start with 1
nomaxvalue --不设置最大值
nocycle  --一直累加,不循环
cache 10;
--创建触发器
create or replace trigger person_id_tri before insert on person
for each row
declare
v_newVal number(12) := 0;
v_incval NUMBER(12) := 0;
BEGIN
IF INSERTING AND :new.id IS NULL THEN
SELECT  person_id_SEQ.NEXTVAL INTO v_newVal FROM DUAL;
-- If this is the first time this table have been inserted into (sequence == 1)
IF v_newVal = 1 THEN
--get the max indentity value from the table
SELECT NVL(max(id),0) INTO v_newVal FROM person;
v_newVal := v_newVal + 1;
--set the sequence to that value
LOOP
EXIT WHEN v_incval>=v_newVal;
SELECT person_id_seq.nextval INTO v_incval FROM dual;
END LOOP;
END IF;
--used to emulate LAST_INSERT_ID()
--mysql_utilities.identity := v_newVal;
-- assign the value from the sequence to emulate the identity column
:new.id := v_newVal;
END IF;
END;

--简单触发器,上面触发器有问题,序列被跳过
create or replace trigger person_id_tri before insert on person
for each row when(new.id is null)
BEGIN
select person_id_seq.nextval into :new.id from dual;
end;

--插入实例
insert into person(name, birth) values('ceshi',sysdate);
--错误的时间格式
insert into person(name,birth) values('hehe','2015-06-02 00:00:00');
--正确的插入日期
insert into person(name,birth) values('hehe',to_date('2005-01-01 13:14:20','yyyy-MM-dd HH24:mi:ss'));
insert into person(name,birth) values('hehe',to_date('2005-01-01','yyyy-MM-dd'));

--oracle 中日期的格式化
select to_date('2005-01-01 13:14:20','yyyy-MM-dd HH24:mi:ss') from dual;

--查询表
select * from person ;

--截断表
truncate table person;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: