简体   繁体   English

包含DECLARE和临时变量的SQL查询

[英]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. 我对SQL还是很陌生,但是尝试编写一个非常复杂的查询,但是在第一部分中失败了。 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. 我需要为表创建一个新行,该表会自动递增ID,并立即提取ID以在查询中进一步使用。 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. 我希望将刚插入的行的ID放入变量@ point1ID,以便以后可以在同一TRANSACTION / COMMIT块中使用它。 What am I doing wrong here? 我在这里做错了什么?

Thanks! 谢谢!

Given that you're using the query in PHP, carry out your INSERT, then use 假设您正在PHP中使用查询,请执行INSERT,然后使用

$insert_id = mysql_insert_id();

to get the auto-incremented ID. 获取自动递增的ID。

I MySQL console you can access the last inserted AUTO_INCREMENT ID with: 在MySQL控制台中,您可以使用以下命令访问最后插入的AUTO_INCREMENT ID:

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. 正如我已经说过的那样,这仅适用于具有AUTO_INCREMENT列的表。 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. 如果将AUTO_INCREMENT列设置为特定的非特殊值,则不会更新此值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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