0

Context

I have a dynamically generated .sql file that contains a series of insert statements which are going to be used for inserting data into many different tables that are dependent on other tables.

After each insert statement is ran, if a particular table has an autoincremented id column, then the text "SET @autoIncrementColumnName = LAST_INSERT_ID();" is generated which stores the last insert id of that insert statement in a mysql variable. Then if there is another INSERT statement for that particular table, the process is repeated. The problem is that each statement "SET @autoIncrementColumnName = LAST_INSERT_ID();" overwrites the previous variable before it is able to use the variable later on in the .sql file.

So then later on in the .sql script where you see two lines like these:

INSERT INTO relatedTable (col1,col2,specialColumn,col3,col4) VALUES ('','',@autoIncrementColumnName,'','');

INSERT INTO relatedTable (col1,col2,specialColumn,col3,col4) VALUES ('','',@autoIncrementColumnName,'','');

It needs to insert the mysql value it stored earlier but all of the variables are being overwritten except for one.

Two Questions

  1. Is it possible to create variable variables using only MYSQL? Like this:

    SET @dynamicVarName = CONCAT('guestCreditCardId', LAST_INSERT_ID()); 
    SET @@dynamicVarName = LAST_INSERT_ID();
    
  2. If variable variables are not possible, what solution could I use?

Dharman
  • 30,962
  • 25
  • 85
  • 135
darga33
  • 401
  • 1
  • 4
  • 10
  • Does this answer your question? [How to declare a variable in MySQL?](https://stackoverflow.com/questions/11754781/how-to-declare-a-variable-in-mysql) – miken32 May 13 '22 at 17:34

1 Answers1

0

While looking deeply into the problem at hand, I found that I was able to avoid headaches by creating multiple functions/methods, each one being responsible for a specific part of the sql generation. That way later down the road, if you needed to create another dynamic sql statement, you can place it where you need to by just calling another function/method from wherever you need to.

For instance

If you have 5 tables you are generating "INSERT INTO" sql statements for, and 3 of those tables have records that are not being used in the creation of other dynamic sql statements, then you can have one function/method handle all tables that don't require data from other tables.

For any special cases

Then create separate functions/methods for special cases.

Dharman
  • 30,962
  • 25
  • 85
  • 135
darga33
  • 401
  • 1
  • 4
  • 10