last day (15 days later) » 

7:20 PM
0
A: MySQL Function with LAST_INSERT_ID() giving unexpected results

Tim3880Lorenz already gave you the solution: SELECT `id` INTO ret FROM state WHERE `name` LIKE dname; IF ret IS NULL THEN INSERT IGNORE INTO state (`name`) VALUES (dname); SELECT `id` INTO ret FROM state WHERE `name` LIKE dname; END IF; If you have multiple calls to the same fun...

 
I'm going with your first option but it doesn't work. Whether the record exists or not, ret is returning NULL and nothing gets inserted. When I switch the if statement to IF ret IS NULL, at least the new state gets inserted but both conditions return ret value of zero. This is so perplexing, I see nothing wrong with the code! I absolutely need to have the new or existing id value returned in ret.
To troubleshoot I have further changed the 2nd "SELECT id into ret..." to "SELECT LAST_INSERT_ID() INTO ret;". Now when the state is new, it returns the new id. The remaining problem is this: when it is an existing state, it is returning ret of zero.
 
Please post your new code.
 
Done so under "my code now"
 
The first return should be "RETURN ret;" Ret2 is not needed
 
I'm aware: this was done to troubleshoot since ret did not work. Do you see the line "insert into debug (dump1,dump2) values ('ret will be',ret);"? Well it's dumping zero in the debug table so right from the start there is a problem getting the ID from the first select statement. I've stared at that statement and see nothing wrong with it. I've run it directly in the MySQL console, replacing 'dname' with an actual value present in the state table and it correctly returns the id. So my thinking is something is wrong with the SELECT INTO but what exactly?
 
7:20 PM
You need dump your insert value to make sure you are calling the function correctly.
 
I've dumped dname as well and it's perfectly fine. I'm at a loss.
 
Try update you full code and top rows in your tables
And change select id into ret to select max(id) into ret
 
not clear what you mean by "Try update you full code and top rows in your tables"
do you mean to share my full code?
Wowwww...found the problem
In my first paste, the function definition was CREATE DEFINER=root@localhost FUNCTION insertindb(itemtype VARCHAR(10), dname VARCHAR (50), id INTEGER, fname VARCHAR(50), lname VARCHAR(50)) RETURNS INT(11)
I changed the id INTEGER to idx INTEGER and it worked. so it must have been a conflict.
Thanks a lot
 
that's why i asked to see your whole function definition.
good luck and enjoy the weekend
 
7:35 PM
Yes that prompted me to scroll upward and look again. Gr8 weekend to you too.
 

last day (15 days later) »