简体   繁体   English

最后一个INSERT ID SQL子查询返回多行

[英]LAST INSERT ID SQL Subquery returns more than one row

I have the below Stored Procedure: 我有以下存储过程:

DELIMITER $$
  DROP PROCEDURE IF EXISTS spCashDonation$$
  CREATE PROCEDURE spCashDonation(IN fname varchar(50),IN lname varchar(50),IN telNo bigint, IN pmode tinyint,IN amt decimal(8,2), OUT rno varchar(20))
    BEGIN
    Set @rmain := (select trim(concat('DNB', DATE_FORMAT(CURRENT_DATE(), '%y'), DATE_FORMAT(CURRENT_DATE(), '%m'))));

  IF ((trim(DATE_FORMAT(CURRENT_DATE(),'%m')) = 01) OR (trim(DATE_FORMAT(CURRENT_DATE(),'%m')) = 1)) THEN
    Set @rpart = 1;
 END IF;

 IF ((trim(DATE_FORMAT(CURRENT_DATE(),'%m')) != 01) OR (trim(DATE_FORMAT(CURRENT_DATE(),'%m')) != 1)) THEN
  Set @rpart := (select coalesce(max(ReceiptPart),0) from Donation) + 1;
 END IF;

 INSERT INTO Donation (ReceiptMain, ReceiptPart, firstName, lastName, telNo, payMode, Amount) VALUES (@rmain, @rpart, fname, lname, telNo, pmode, amt);

 Set @lid := (select LAST_INSERT_ID()from donation);
 select concat(ReceiptMain,ReceiptPart) into rno from donation where id = @lid;

 END$$
 DELIMITER ;

Call spCashDonation ('RAJIV','IYER',7506033048,0,1000,@rno);
select @rno;

When the table has no record, the first insert goes through fine. 当表没有记录时,第一个插入没有记录。 The upon the second insert it throws an error as 在第二个插入时,它会抛出一个错误

Error Code: 1242. Subquery returns more than 1 row 错误代码:1242。子查询返回超过1行

When I query for the last insert id, I get more than 1 value. 当我查询最后一个插入ID时,我得到的值超过1。 So, I modified the last part of the procedure to: 所以,我修改了程序的最后一部分:

Set @lid := (select max(LAST_INSERT_ID()) from donation); 设置@lid:=(从捐赠中选择max(LAST_INSERT_ID());

Please advice, if this is fine as it should not hinder any concurrent inserts and future CRUD operations. 请提供建议,如果这样可以,因为它不应该妨碍任何并发插入和未来的CRUD操作。 Thanks in advance. 提前致谢。

Set @lid := (select LAST_INSERT_ID() from donation); 

In the above line remove the FROM statement. 在上面的行中删除FROM语句。 If more than one record in the Donation table it will return the same number of times the LAST_INSERT_ID() value. 如果Donation表中有多个记录,它将返回与LAST_INSERT_ID()值相同的次数。

So simply use Set @lid := (SELECT LAST_INSERT_ID()); 所以只需使用Set @lid := (SELECT LAST_INSERT_ID()); it will work in your case. 它会适用于你的情况。

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

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