1

I have a table in MySql table like the following

row_timestamp timestamp
, row_id int(11) auto_increment
, mrn char(17)
, patients_last_name varchar(50)
, patients_first_name varchar(50)
, ssn char(4) default '0000'
, visit_key NULL

upon the insertion of a record, I'd like visit_key to bet set to visit_key = concat(mrn, row_id) I was trying to accomplish this with a before insert trigger to no avail, I kept getting that the mrn column was not in the field select list.

Update

I tried the following, which seems not to work because the auto_increment has not yet incremented:

set new.visit_key = concat(new.mrn, new.row_id)

I also tried

set new.visit_key = concat(new.mrn, max(row_id)+1)

I am thinking of the trigger to sort of act like a calculated field in MS Access, is this reasonable? Thoughts? Would it not be possible to do since the visit_key would technically be NULL and you cannot update a new value?

UPDATE

I used the following code that I adapted from this question here

DELIMITER //
CREATE TRIGGER vkt AFTER INSERT ON demographic_information
FOR EACH ROW
BEGIN
  UPDATE `demographic_information` SET visit_key_test = concat(new.mrn, mew.row_id) WHERE row_id = NEW.row_id;
END;
//
DELIMITER ;

and got the following error message:

INSERT INTO  `manchuco_nys_trauma`.`demographic_information` (

`row_timestamp` ,
`row_id` ,
`mrn` ,
`patients_last_name` ,
`patients_first_name` ,
`ssn` ,
`visit_id` ,
`visit_key_test`
)
VALUES (

CURRENT_TIMESTAMP , NULL ,  '123456',  'Sanderson',  'Steven',  '1234',  '12345670', NULL
)
MySQL said: Documentation

#1442 - Can't update table 'demographic_information' in stored function/trigger because it is already used by statement which invoked this stored function/trigger. 

Thank you,

Community
  • 1
  • 1
MCP_infiltrator
  • 3,961
  • 10
  • 45
  • 82

2 Answers2

0

Try selecting the auto increment value inside the trigger:

CREATE TRIGGER trigger_name AFTER INSERT ON yourTable FOR EACH ROW
BEGIN
    DECLARE next_id integer;
    SET next_id = (SELECT AUTO_INCREMENT
                   FROM information_schema.TABLES
                   WHERE TABLE_SCHEMA='yourDB' AND TABLE_NAME='yourTable');
    SET new.visit_key = CONCAT(new.mrn, next_id);
END

I discovered this approach in this SO article.

Community
  • 1
  • 1
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

What you observe seems normal: since you're using BEFORE INSERT the id value doen't exist yet.
And the same applies for your try with concat(new.mrn, **new**.row_id): NEW has no sense at the moment.

So I suggest you use AFTER INSERT instead.

cFreed
  • 4,404
  • 1
  • 23
  • 33