3

我有一个存储过程,它在一张表中进行保存操作。在这个存储过程中,我在表中插入多条记录。

这是我的表结构

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,我现在正在使用事务。

4

0 回答 0