SQL Check Constraint - How to check for specific format?

2.8k views Asked by At

I am trying to add a CHECK constraint to my column for a football game score. The format has to be like such --> 4-2 (with the hyphen) Also both numbers cannot exceed 999.

Below is what I have so far which obviously does not work..Any ideas? Column data type is VARCHAR(7)

Constraint ScoreCheck CHECK(Score LIKE '0-999'-'0-999'); 
2

There are 2 answers

2
Gordon Linoff On

The correct way to do this is to use a view or virtual column. Virtual columns are available since 11g. Simply define the virtual column in the table, such as:

create table  . . . 
    WinningScore int,
    LosingScore int,
    GameScore as (WinningScore || '-' || LosingScore)
)

(You can also use alter table for an existing table.)

Here is a bit of a primer on virtual columns.

0
Dhruv Raj Singh Rathore On

Instead of LIKE you should use REGEXP_LIKE

Constraint ScoreCheck CHECK( REGEXP_LIKE(Score,'^[0-9]{1,3}-[0-9]{1,3}$');

Also for further use, you should split this field into home team score and away team score and store them as integer so processing them would be easy