简体   繁体   中英

Oracle SQL constraint to check data before allowing INSERT

kinda new to SQL, so need some help here. Firstly, please refer to the picture for my tables (BED table, WARD table, PATIENT table).

I am using Oracle SQL Developer Version 19.4.0.354 as a learning tool.

=====================================================================

EDIT: So i have changed the tables as like below:

BED( BEDNO, BED_OCCUPIEDDATE , WARDNO, PATIENTNO)

PATIENTS( PATIENTNO , FIRSTNAME, LASTNAME, ADDRESS, GENDER, DATEOFBIRTH, MARITALSTATUS, PHONENO, REGISTEREDDATE, WAITINGLISTDATE, EXPECTEDSTAY, DATEWARDED, EXPECTEDLEAVE, DATELEFT)

WARD( WARDNO , WARDNAME, LOCATION, NUMBEROFBED, EXTNO)

BedNo is unique in the entire database. numbered from 1-240. Meaning WardA will have bedno 1-10, WardB might have bedno 11-20 and so on.

How would i be able to allow allocation of patient to a ward only if there are bed available in the ward? Because currently, beds are not "tagged" to the ward if you refer to my ERD.

Change the design a little.

First have the wards' table.

CREATE TABLE ward
             (wardno ...,
              ...
              PRIMARY KEY (wardno)
              ...);

Then in the beds' table reference the ward who attends this bed but not the patient that occupies it.

CREATE TABLE bed
             (bedno ...,
              wardno ...,
              ...
              PRIMARY KEY (bedno),
              FOREIGN KEY (wardno)
                          REFERENCES ward
                                     (wardno),
              ...);

In the patients' table reference the bed a patient occupies. A non existing bed cannot be referenced and without a bed a patient doesn't get a ward. By declaring the refereed bed unique, no more than one patient can occupy the same bed. If you don't want any patients without a bed, you can also declare the bed reference NOT NULL .

CREATE TABLE patient
             (patientno ...,
              ...
              bedno ... NOT NULL,
              PRIMARY KEY (patientno),
              FOREIGN KEY (bedno)
                          REFERENCES bed
                                     (bedno),
              UNIQUE (bedno),
              ...);

And by the way, you shouldn't materialize the number of beds a ward attends, if that is what ward.numberofbed is supposed to store. Instead you should query that figure when needed. For convenience you can also use a view, so you don't need to repeat such a query.

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