insertId coming as 0 for all records after a query followed by a stored procedure call in a transaction
Stored Function
It's a while loop and should return multiple insert id's
CREATE FUNCTION `day`(start DATE, end DATE, event_id INT) RETURNS int(11)
BEGIN
DECLARE
insertId INTEGER;
WHILE start <= end DO
INSERT INTO day(date, event_id) VALUES(start, event_id);
SET insertId = LAST_INSERT_ID();
SET start = start + 1;
END WHILE;
RETURN insertId;
END
Node.js code
* Insert query
connection.beginTransaction(...
var query = "INSERT INTO event(name, active, description, appId) VALUES(?, ?, ?, ?)";
self.connection.query(query,
* stored procedure call (within same transaction)
please also help to rewrite this if it's incorrect, I tried to use connection.query array for the parameters but having problems.
var query = "SET @start = '" + request.body.from + "'; \
SET @end = '" + request.body.to + "'; \
SET @event_id = " + rows.insertId + "; \
CALL day(@start, @end, @event_id);";
`this.connection.query(query, [], function(error, rows, fields) {`
`console.log(rows)`
Console output
first 3 records are from stored procedure, the last one from the query or vice versa
[
{
"fieldCount": 0,
"affectedRows": 0,
"insertId": 0,
"serverStatus": 11,
"warningCount": 0,
"message": "",
"protocol41": true,
"changedRows": 0
},
{
"fieldCount": 0,
"affectedRows": 0,
"insertId": 0,
"serverStatus": 11,
"warningCount": 0,
"message": "",
"protocol41": true,
"changedRows": 0
},
{
"fieldCount": 0,
"affectedRows": 0,
"insertId": 0,
"serverStatus": 11,
"warningCount": 0,
"message": "",
"protocol41": true,
"changedRows": 0
},
{
"fieldCount": 0,
"affectedRows": 1,
"insertId": 0,
"serverStatus": 3,
"warningCount": 0,
"message": "",
"protocol41": true,
"changedRows": 0
}
]
Expectation/Question
All insertId's are 0 How do I get insertId for each inseration in the console output
Hi @casamm ! I'm sorry I have not gotten back to you yet, but I'm inclined to say this is just how MySQL itself works; you see the insertId property is just literally the value the SQL server sent to us, so there isn't much control we have over it or any real way we can influence the value that I know of. If you do, a PR would be great!