简体   繁体   中英

SQL query involving DECLARE and temporary variables

I'm fairly new to SQL, but trying to write quite a complicated query, but it's failing at the first part. I need to create a new row for a table that auto increments the ID, and immediately extract the ID to use further down the query. Have been googling for hours to try and understand this, but can't seem to get it to work. Here is the opening bit (which it is failing on it seems):

DECLARE @point1ID;
INSERT INTO points SET
pointName = "$pointName1",
street = "$street1",
town = "$town1",
city = "$city1",
zip = "XXX",
country = "$country1",
pointDescription = "$pointDescription1";
SELECT @point1ID = scope_identity();

I was hoping that would put the ID of the just-inserted row into the variable @point1ID, so that I could use it later on in the same TRANSACTION / COMMIT block. What am I doing wrong here?

Thanks!

Given that you're using the query in PHP, carry out your INSERT, then use

$insert_id = mysql_insert_id();

to get the auto-incremented ID.

I MySQL console you can access the last inserted AUTO_INCREMENT ID with:

SELECT LAST_INSERT_ID();

If you would like to store this information in a variable for future use:

SET @lastid = LAST_INSERT_ID();

As I already said that will work only for tables which has AUTO_INCREMENT column. Also this value is maintained on the server side and only for this connection. This value is not updated if you set an AUTO_INCREMENT column to a specific nonspecial value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM