简体   繁体   中英

mySQL creating multiple temporary tables

I have a Stored Procedure in mySQL that takes a subset of data from a table and performs some analysis on that subset within a temp table. Here is my code:

CREATE PROCEDURE GetPortfolioStats
(
    InIdx_i     INT,
    InStart_i   INT,
    InEnd_i     INT
)
BEGIN

DECLARE myLimit     INT;
DECLARE myOffset    INT;

SET myLimit = InEnd_i - InStart_i + 1;
SET myOffset = InStart_i - 1;

CREATE TEMPORARY TABLE IF NOT EXISTS myTmpTable AS (SELECT * FROM Leases WHERE Portfolio_i = InIdx_i ORDER BY Index_i LIMIT myLimit OFFSET myOffset);

SET @Additive_i := (SELECT COUNT(Index_i) FROM myTmpTable WHERE ReviewType_vc = 'Additive');
DROP TABLE myTmpTable;

SELECT @Additive_i;

END; GO

This works fine. However, the problem I have is that this is a multi-threaded application and when multiple threads are calling this stored proc, they start sharing the same temp table, which messes up the Stats I'm trying to compile.

Is there a way to either apply a unique table name to each call of the stored proc or limit the scope of the temp table to just that instance of the stored proc?

To answer the specific question: the easiest solution would be to use a different database connection per thread because temporary tables are session (connection) specific :

You can use the TEMPORARY keyword when creating a table. A TEMPORARY table is visible only to the current session, and is dropped automatically when the session is closed. This means that two different sessions can use the same temporary table name without conflicting with each other or with an existing non-TEMPORARY table of the same name.

However, after checking out the actual code, I would suggest not to use a temporary table at all, use a single query with a subquery:

SELECT COUNT(Index_i)
FROM
    (SELECT Index_i, ReviewType_vc
     FROM Leases
     WHERE Portfolio_i = InIdx_i
     ORDER BY Index_i
     LIMIT myLimit OFFSET myOffset) t
WHERE ReviewType_vc = 'Additive'

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