Assuming your OS
table is something like:
CREATE TABLE OS
(
ID INTEGER,
STATUS BOOLEAN
);
INSERT INTO OS ( ID, STATUS ) VALUES ( 100, TRUE );
INSERT INTO OS ( ID, STATUS ) VALUES ( 200, FALSE );
INSERT INTO OS ( ID, STATUS ) VALUES ( 300, TRUE );
INSERT INTO OS ( ID, STATUS ) VALUES ( 400, FALSE );
1) An auxiliary column is created in the table with the desired type:
ALTER TABLE OS ADD COLUMN STATUS_AUX SMALLINT;
2) Converts the pre-existing data in the original column to the auxiliary column appropriately:
UPDATE OS SET STATUS_AUX = 0 WHERE STATUS = FALSE;
UPDATE OS SET STATUS_AUX = 2 WHERE STATUS = TRUE;
3) Exclude the original column:
ALTER TABLE OS DROP COLUMN STATUS;
4) The auxiliary column is renamed to the original column name:
ALTER TABLE OS RENAME COLUMN STATUS_AUX TO STATUS;
5) A% check% is included in the CONSTRAINT
table to ensure data integrity of the OS
field (0, 1 or 2):
ALTER TABLE OS ADD CONSTRAINT chk_os_status CHECK ( STATUS = 0 OR STATUS = 1 OR STATUS = 2 );
6) Optionally, the STATUS
field can be STATUS
:
ALTER TABLE OS ALTER COLUMN STATUS SET NOT NULL;
Entering data:
INSERT INTO OS ( ID, STATUS ) VALUES ( 500, 0 ); -- OK!
INSERT INTO OS ( ID, STATUS ) VALUES ( 600, 1 ); -- OK!
INSERT INTO OS ( ID, STATUS ) VALUES ( 700, 2 ); -- OK!
Testing NOT NULL
:
INSERT INTO OS ( ID, STATUS ) VALUES ( 800, 3 ); -- ERRO! (CHECK CONSTRAINT)
Testing CONSTRAINT
:
INSERT INTO OS ( ID, STATUS ) VALUES ( 900, NULL ); -- ERRO! (NOT NULL)
Running on SQLFiddle