---
title: "触发器Helloworld"
author: "bepatient"
date: "2011-05-06T21:32:50Z"
tags: ["Cache", "Oracle", "笑话"]
categories: ["数据库"]
slug: "helloworld"
draft: false
lastmod: "2011-05-06T21:34:22Z"
id: 1034873
url: "https://bepatient.iteye.com/blog/1034873"
---

今天想弄一个oracle中触发器的helloworld，结果弄了很久才弄好。

这个触发器的功能是插入表数据主键自增长。

建表：

```
-- Create table
create table AUTO_INCREASE
(
  ID   NUMBER not null,
  NAME VARCHAR2(30)
)
tablespace USERS
  pctfree 10
  initrans 1
  maxtrans 255
  storage
  (
    initial 64
    next 1
    minextents 1
    maxextents unlimited
  );
-- Create/Recreate primary, unique and foreign key constraints 
alter table AUTO_INCREASE
  add constraint AUTO_INCREASE_PK primary key (ID)
  using index 
  tablespace USERS
  pctfree 10
  initrans 2
  maxtrans 255
  storage
  (
    initial 64K
    next 1M
    minextents 1
    maxextents unlimited
  );
```

 建立序列：

```
-- Create sequence 
create sequence AUTO_INCREASE_SEQUENCE
minvalue 1
maxvalue 90000
start with 41
increment by 1
cache 20;
```

 建立触发器：

```
CREATE OR REPLACE TRIGGER increase_trigger
  BEFORE INSERT ON auto_increase
  FOR EACH ROW
  when (new.id is null)
begin
select auto_increase_sequence.nextval  into :new.id from dual;
end;
```

 然后像表中插入数据时别插入主键，这是触发器就会自动新增一个序列主键。

之所以弄了很久，是因为new.id一直以为new是表名 ，还有new前面的：号 ，所以......闹笑话了