0

I have an SQL query I can run that looks like:

SELECT
   SUBSTRING_INDEX(SUBSTRING_INDEX(name, ' ', 1), ' ', -1) AS first_name,
   If(  length(name) - length(replace(name, ' ', ''))>1,  
       SUBSTRING_INDEX(SUBSTRING_INDEX(name, ' ', 2), ' ', -1) ,NULL) 
           as middle_name,
   SUBSTRING_INDEX(SUBSTRING_INDEX(name, ' ', 3), ' ', -1) AS last_name
FROM people

While this is works great to split up the full name into first_name, middle_name, and last_name I need a way to have this done automatically; can't go in and run the query and manually update the table each time a person is added.

I've tried to play around with this query in the form of a trigger but keep getting errors, generally the error states "Not allowed to return a result set from trigger"

Any help getting this working would be great

1

1 Answer 1

0

In a BEFORE INSERT trigger, use the qualifier NEW. to reference values assigned to columns of the row being inserted. For example, NEW.col would reference the value supplied for the column col.

Assign a value (or expression) to NEW.col to replace the value supplied for column col, and the value assigned will be inserted instead.

A trigger to accomplish something similar to SELECT statement would look something like this:

DELIMITER $$

CREATE TRIGGER mytrigger 
BEFORE INSERT ON mytable
FOR EACH ROW
BEGIN

   SET NEW.first_name  = SUBSTRING_INDEX(SUBSTRING_INDEX( NEW.name, ' ', 1), ' ', -1);

   SET NEW.last_name   = SUBSTRING_INDEX(SUBSTRING_INDEX( NEW.name, ' ', 3), ' ', -1);

   SET NEW.middle_name = IF(LENGTH( NEW.name) - LENGTH(REPLACE( NEW.name, ' ', ''))>1
       ,SUBSTRING_INDEX(SUBSTRING_INDEX( NEW.name, ' ', 2), ' ', -1)
       ,NULL);

END$$

DELIMITER ;

The error you are getting:

Error: 1415 SQLSTATE: 0A000 (ER_SP_NO_RETSET)
Message: Not allowed to return a result set from a %s

Is due to a documented restriction that applies to both FUNCTION and TRIGGER. (This restriction also applies to a PROCEDURE that is called from the context of a FUNCTION or TRIGGER.)

1
  • @jzg.dev: I didn't do any testing on that, I just copied the expressions you had in the SELECT statement, and gave an example of what a BEFORE INSERT trigger might look like. (You'll want to consider whether you need a corresponding BEFORE UPDATE trigger, if keeping these columns "in sync" is important. In a BEFORE UPDATE trigger, the current value of the columns is available by qualifying with OLD., for example IF ( NEW.col <=> OLD.col ) to compare the new value with the existing value. Sep 11, 2014 at 2:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.