0

I am student

i doing assignement , do auto increment

How to create an auto increment in Oracle ?

CREATE TABLE mua_thi ( mamuathi varchar2(10) not null, check(mamuathi like 'MT%') ) mamuathi = MT + auto_increment; create or replace trigger tangmuathi before insert or update on mua_thi begin set new.mamuathi := MT + muathitang.nextval from Dual; end; create sequence muathitang start with 1 increment by 1; 

1 Answer 1

2
mamuathi = MT + auto_increment; 

Don't structure your table like that. That's a smart key (a single string with several components concatenated). Smart keys are dumb. If the "MT" is crucial (why have a key with a hardcoded, unchanging element?) make it a separate column.

CREATE TABLE mua_thi ( mamuathi varchar2(2) not null , id number (8) not null , primary key (mamuathi, id ) , check(mamuathi = 'MT') ); 

Actually there's still some bad practice there. One, name the constraints - it makes life easier:

, constraint mt_pk primary key (mamuathi, id ) , constraint mt_ck check(mamuathi = 'MT') 

Two, if mamuathi is genuinely a constant it's pointless using it in the key:

, constraint mt_pk primary key ( id ) 

Three, mamuathi may evolve to several values , so think about whether a foreign key to a look-up table might be better.

Obviously the drawback to splitting a smart key is the need to refrence multiple columns. In 11g we can use the virtual column feature to avoid that inconveience:

CREATE TABLE mua_thi ( mamuathi varchar2(2) not null , id number (8) not null , mamuathi_disp AS mamuathi||lpad(id,8,'0') , primary key (mamuathi, id ) , check(mamuathi = 'MT') ); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.