4

I have a table where I auto-generate a binary(16) Id by having this in my defaultExpression:

(uuid_to_bin(uuid(), true))

I created a store procedure and insert values to that table and figured I could retrive the latest value by using LAST_INSERT_ID() but Im getting the value 0 instead.

Example:

DECLARE userId BINARY(16);

INSERT INTO Users (Email, Password, FirstName, LastName, Age, Jobtitle, ImageId, PrefLang, ChangedPassword)
VALUES ('email', 'Hashpassword', 'firstName', 'lastName', 'age', 'jobTitle', 'imageId', 'prefLanguagId', 0);

SET userId = LAST_INSERT_ID(); // not getting the correct value here

Trying to use the value above in a junction table:

  INSERT INTO UserRoles (UserId, RoleId)
    VALUES (userId, roleId);

Error Code: 1452 Cannot add or update a child row: a foreign key constraint fails (`dbName`.`userroles`, CONSTRAINT UserIdRef FOREIGN KEY (`UserId`) REFERENCES `users` (`Id`))

How can I solve this?

2
  • 1
    You can only use LAST_INSERT_ID() when using an auto increment column. Commented May 11, 2020 at 20:08
  • Im more use to working in a sql enviorment and thought it would be the same as IDENTIY. Only way to solve this is by adding the UUID manualy in the sp? Commented May 11, 2020 at 20:10

1 Answer 1

4

LAST_INSERT_ID() only gets an ID that was assigned using AUTO_INCREMENT. It won't return an ID that was assigned using a DEFAULT expression.

You'll need to calculate the ID in your procedure rather than using the default.

SET userId = uuid_to_bin(uuid(), true);
INSERT INTO Users (userId, Email, Password, FirstName, LastName, Age, Jobtitle, ImageId, PrefLang, ChangedPassword)
    VALUES (userId, 'email', 'Hashpassword', 'firstName', 'lastName', 'age', 'jobTitle', 'imageId', 'prefLanguagId', 0);
INSERT INTO UserRoles (UserId, RoleId)
    VALUES (userId, roleId);
Sign up to request clarification or add additional context in comments.

1 Comment

Did not know that this was not possible. I firgured that the above would be solution as soon as I read you comment. Probably good to save this question a a future reference.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.