简体   繁体   中英

Oracle SQL CHECK CONSTRAINT VARCHAR

How can I do a constraint that will check first two values and second two values in different ranges? I have to put time in database, but i do not need a data, that's why I don't want to use DATETIME type. I need only a TIME, but as far as I know there is no TIME datatype in Oracle.

My column looks like:

visit_hours VARCHAR(4) 

so the first 2 characters will be 00 to 23, and the second 2 characters will be 00 to 59, so I can store a time from 00:00 to 23:59.

How can I do that? I already found something like regular expressions, but I don't know how to implement it in this example.

CONSTRAINT check_time CHECK (regexp_like(visit_hours, '?????') );

Any help appreciated.

I'd probably do something like

CONSTRAINT check_time CHECK( to_number( substr( visit_hours, 1, 2 ) ) BETWEEN 0 AND 23 AND
                             to_number( substr( visit_hours, 3, 2 ) ) BETWEEN 0 AND 59 );

substr( visit_hours, 1, 2 ) gives you the first two characters in the string, substr( visit_hours, 3, 2 ) gives you the third and fourth character. Convert both to numbers with the to_number function and then verify the range.

I have to put time in database, but i do not need a data, that's why I don't want to use DATETIME type

You don't have to worry about date and time portion separately. A DATE data type will have both the portions and all you need is use to_char with proper format model .

So, you can have the column as -

visit_hours DATE

Edit As Jeffrey and Ben said, the constraint is not needed when data type is DATE . Just follow what I explained above.

You don't need any constraint - just use the DATE datatype, it stores time values as well. Your application can extract the time using TO_CHAR(visit_hours, 'HH24:MI') and ignore the date part and the seconds part.

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