简体   繁体   中英

How to set the default value for only positive time

I have column with TIME type( 00:00:00 ). I want to allow only positive values. So, -05:30:00 , for example, would be invalid.

Is there a way of doing it?

I want to set a DEFAULT VALUE for the column, so if it recieve '-05:00:00' value it will set the value to '00:00:00'.

You can depend on time_format( time, format ) and if required on date_format( date, format ) functions in MySQL . You also require substring and locate functions to parse.

To set a time field to with default or +ve part of time data, following examples helps you:

mysql> set @time_value='-23:51:48';
Query OK, 0 rows affected (0.00 sec)

Example 1 :

mysql> insert
         into time_table( time_field )
         values ( if( locate( '-', @time_value ) = 1, '00:00:00', @time_value ) );
Query OK, 1 row affected (0.00 sec)  

Let us see what is inserted:

mysql> select time_field from time_table;
+------------+
| time_field |
+------------+
| 00:00:00   |
+------------+
1 row in set (0.00 sec)

Example 2 :

mysql> insert
         into time_table( time_field )
         values ( substring( @time_value, ( locate( '-', @time_value ) + 1 ) ) );
Query OK, 1 row affected (0.00 sec)  

Example 3 :

mysql> insert
         into time_table( time_field )
         values
          ( substring( time_format( @time_value, '%H %k:%i:%s' ),
                       ( locate( ' ', time_format( @time_value, '%H %k:%i:%s' ) ) + 1 )
                     ) 
          );
Query OK, 1 row affected (0.00 sec)  

In this:

  1. H : for Hour to return as 00 to 23
  2. k : for Hour to return as 0 to 23
  3. i : for Minutes, numeric 00 to 59
  4. s : for Seconds to return as 00 to 59

Let us see what is inserted:

mysql> select time_field from time_table;
+------------+
| time_field |
+------------+
| 23:51:48   |
+------------+
1 row in set (0.00 sec)

For more details on format specifier characters like %k refer to date_format( date, format )

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