user2027231
user2027231

Reputation: 169

MySql Insert and Select All In One

What I want to do is insert a record into a table and return the primary key in a select statement in the same query. The primary key is a auto increment and I would like to get this value to send to another function.

Upvotes: 0

Views: 62

Answers (2)

gen_Eric
gen_Eric

Reputation: 227240

You cannot do both of these in one query. What you can do instead is use LAST_INSERT_ID() in your second query.

INSERT INTO tableA(rowA, rowB) VALUES('a', 'b');

SELECT * FROM tableB WHERE rowID = LAST_INSERT_ID();

Upvotes: 1

CloudyMarble
CloudyMarble

Reputation: 37566

You can create a function which inserts and returns the Id Value if the new data row, something like this:

CREATE FUNCTION INSERTANDRETURN(Data to enter as parameters)
  RETURNS INT
  DETERMINISTIC
   BEGIN
    DECLARE id INT;
    -- Insert data
    SET id = last id according to Maxvalue or last inserted data
    RETURN id;
   END

See the documentation for further reading about procedures and functions

Upvotes: 0

Related Questions