简体   繁体   中英

Constraint in oracle

CREATE TABLE classname (
class_name VARCHAR2(5) CONSTRAINT class_name_pk PRIMARY KEY,
meet_at_and_timing VARCHAR2(30),
room_no VARCHAR2(5),
faculty_handling NUMBER(5) CONSTRAINT faculty_handling_fk REFERENCES faculty(faculty_id)
);

in the above table creation the room_number should always contain "LH" as first two characters.

Example:

room_no=LH43 is valid but room_no=EC43 is invalid...

how should i specify this?

I guess it will be simpler

alter table classname
     add constraint check_room_no 
      check (SUBSTR(room_no, 1, 2) = 'LH');

The most simple syntax would be:

alter table classname
 add constraint check_room_no 
  check (room_no like 'LH%');

I prefer this method because if you were querying for strings beginning LH then you'd most likely use this, not SubStr()

All three solutions are good. I've created a test table with 200 millon rows and measured the time it takes to add a check constraint:

 36.4s  0.17 us   CHECK (room_no LIKE 'LH%')
 54.2s  0.26 us   CHECK (substr(room_no,1,2) = 'LH') 
111.9s  0.54 us   CHECK (REGEXP_LIKE(room_no, '^LH', 'c'))
138.3s  0.66 us   CHECK (REGEXP_LIKE(room_no, '^LH', 'i'))

You should make use of REGEXP_LIKE. If you want "LH" uppercase, you should specify it is case sensitive in REGEXP_LIKE.

alter table classname
     add constraint check_room_no 
      check (REGEXP_LIKE(room_no,'your_regex_goes_here','C'));

Then you figure out what the regex is for your constraint by playing with http://www.gskinner.com/RegExr/ for instance.

example :

 alter table classname
    add constraint check_room_no 
      check (REGEXP_LIKE(room_no,'^LH\w','C'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM