我有一个存储过程,它在一个表中执行保存操作。 在这个存储过程中,我在表中插入多个记录。
这是我的表结构
Table : InviteMst
~~~~~~~~~~~~~~~~~
Name DataType Description
-------- ------------ ----------------------
InviteID Int PrimaryKey (Auto Incr)
Date Date
UserID Int (ForignKey)
EMailID varchar(50)
Guid varchar(36)
store procedure : usp_InviteMst
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CREATE PROCEDURE `usp_InviteMst`( IN n_UserID INT, IN EmailList MEDIUMTEXT )
BEGIN
DECLARE d_Date DATETIME DEFAULT NOW();
IF LENGTH(EmailList) > 0 THEN
SET @sqlQuery = "";
SET nPos = INSTR(EmailList, ",");
WHILE (nPos <> 0) DO
SET c_EmailID = TRIM(SUBSTRING(EmailList, 1,nPos - 1));
IF c_EmailID <> "" THEN
SET c_Guid = "";
//Here I am checking that If User already exists with same emailid in same date or note.
SELECT Guid INTO c_Guid
FROM InviteMst
WHERE UserID = n_UserID
AND Date = DATE(d_Date)
AND Guid IS NOT NULL
AND EMailID = c_EmailID
ORDER BY Date DESC
LIMIT 0, 1;
SET c_Guid = COALESCEc_Guid ,"");
IF (c_Guid = "") THEN
SET c_Guid = UUID();
//Here I am preparing statement/query for insert
SET @sqlQuery = CONCAT(@sqlQuery, IF(LENGTH(@sqlQuery) > 0,",",""), "(", n_UserID, ", '", d_Date, "','", c_EmailID, "', c_GuID, "') ");
END IF;
END IF;
SET EmailList = SUBSTRING(EmailList, nPos +1, LENGTH(EmailList));
SET nPos = INSTR(EmailList, ",");
END WHILE;
IF (LENGTH(@sqlQuery) > 0) THEN
//Finally here I am inserting in table
SET @sqlQuery = CONCAT("INSERT INTO InviteMst ( UserID, Date, EmailID, Guid ) VALUES ", @sqlQuery);
PREPARE stmt FROM @sqlQuery;
EXECUTE stmt;
SET @sqlQuery = "";
END IF;
END IF;
END
我正在调用这样的商店程序:
call usp_InviteMst( 1, 'a@a.com,b@b.com,c@c.co.in,g@yahoo.com' );
在可能的情况下,它工作得很完美,但有时候(在我的实际项目中)它会出现错误'锁定等待超时超出'。 我的'innodb_lock_wait_timeout'设置为100。
如果有更好的方法可以做到这一点。或者如何在单个请求中插入多个记录。
我正在使用node.js,我现在正在使用交易。