Total Pageviews

2014/08/28

[Oracle] How to Create Before Insert Trigger

Requirement
Here has one of my table schema, and the first column, SEQ_NO, will be assigned serial number which value will be get from SE_FMS_CF0006 sequence.

I hope I do not need get the sequence value manually and assign to SEQ_NO column manually.

Column
Type
Size
Nulls
Default
Comments
SEQ_NO
number
20
流水號SELECT SE_FMS_CF0006.NEXTVAL FROM DUAL
AGE
varchar2
7
 √ 
null
資料提供機構代碼
FILE_TYPE
varchar2
8
 √ 
null
傳輸檔案識別
PDATE
varchar2
7
資料日期
FYR
varchar2
3
 √ 
null
會計年度
ACC
varchar2
11
科目代碼
ACC_APPENDIX
varchar2
3
科目代碼附加碼
AMOUNT
number
15,2
 √ 
0
金額
UPDATE_DATE
timestamp(6)
11,6
 √ 
now
更新日期
USER_ID
varchar2
20
 √ 
null
異動者


Solution
We can make good use of trigger to fulfill this requirement, you can check the before insert trigger. 
As you do insert, you can skip SEQ_NO, this trigger will get the serial number before you do insert.
CREATE OR REPLACE TRIGGER AP_PSR.TR_BI_CF0006  
  BEFORE INSERT ON AP_PSR.CF0006  FOR EACH ROW  
 BEGIN  
  IF :NEW.SEQ_NO IS NULL THEN  
   SELECT SE_FMS_CF0006.NEXTVAL INTO :NEW.SEQ_NO FROM DUAL;  
  END IF;  
 END;  

Demo
Assume I would like to execute the insert statement, I only provide values to mandatory columns except SEQ_NO.

INSERT INTO cf0006(pdate, acc, acc_appendix)
VALUES('1030401', '123', '123');
Then execute the select statement:
SELECT * FROM cf0006;

See.... I did not assign any value to SEQ_NO, its value assigned by TR_BI_CF0006  trigger automatically.


Reference
[1] http://www.techonthenet.com/oracle/triggers/before_insert.php

No comments: