Question

So my problem is the following. I've got a timeStatus column that will have one of two values on an INSERT statement, 'pending' or 'never', depending on whether the column fromDate is NULL or not.

I've made this prepared statement that doesn't work but represents what I intend. On the other hand I'm not sure if a constraint would be in order here, rather then having it specified on the statement. This way I could specify the status value for an insert or update and the table would know what to do. However I need some guidance as to what method to go with and where to go to learn it.

Here's the statement:

INSERT INTO Bservices (
  servStatus, timeStatus,
  fromDetails, fromDate, fromTime) 
VALUES(
  'pending', IF(ISNULL(`fromDate`)) 'pending' ELSE 'never', 
  'a', '', '')

The intended behavior is the following:

ON INSERT
if(fromDate == '') { 
  timeStatus = 'pending' 
} else { 
  timeStatus = 'never' 
}

ON UPDATE
if(timeStatus == 'pending' && fromDate != '') { 
  timeStatus = 'updated'
}
Was it helpful?

Solution

This doesn't work when you do it with expressions in the VALUES clause of an INSERT statement, because the expressions are evaluated before the row has been created. Therefore all columns are naturally NULL.

To do what you want, you need to write triggers BEFORE INSERT and BEFORE UPDATE. Something like the following, though I have not tested this so I'll leave debugging up to you:

CREATE TRIGGER insBservices
BEFORE INSERT ON Bservices 
FOR EACH ROW
  SET NEW.timeStatus = IF(NEW.fromDate IS NULL, 'pending', 'never');

CREATE TRIGGER updBservices
BEFORE UPDATE ON Bservices
FOR EACH ROW
  SET NEW.timeStatus = IF(NEW.fromDate IS NOT NULL AND OLD.timeStatus = 'pending', 
      'updated', NEW.timeStatus);

Re your comment:

If you want to learn more about triggers, the MySQL manual is actually pretty weak in this area. They show you the syntax for reference, but not many examples. There are a lot of tricky parts.

For example, understanding when to use DELIMITER when you define triggers, to account for the ambiguity between semicolons inside the body of a trigger, versus the terminator of the CREATE TRIGGER statement itself. This applies to CREATE PROCEDURE and CREATE FUNCTION as well.

I wrote an example and an explanation in my answer to Create function through MySQLdb.

There are tutorials on triggers, for example:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top