views:

41

answers:

1

I'm looking at a database that has 3 tables into which I have to insert data:

resource
  id (AUTO_INCREMENT)
  name

resource_item
  id (AUTO_INCREMENT)
  name
  resource_id (FK ref resource.id)

resource_item_business_function
  id (AUTO_INCREMENT)
  business_function_name
  resource_item_id

What I'm struggling with is the fact that this must be scripted. I'm only inserting 1 resource record so I can script the insert into the resource table easily enough. I have ~20 resource_item records to insert for that resource and I can even do that easily enough using the LAST_INSERT_ID() function. The question is...how do I insert into resource_item_business_function?

I have no idea how to insert the proper resource_item_id into each resource_item_business_function record. Any thoughts would be much appreciated.

A: 

You would need to use LAST_INSERT_ID() after each insert into resource_item. So your final script could look something like this:

SET AUTOCOMMIT=0;
SET @RESOURCE_ID=0;

INSERT INTO resource ( NULL, "Some Name");
SELECT LAST_INSERT_ID() INTO @RESOURCE_ID;

INSERT INTO resource_item ( NULL, "Some Name", RESOURCE_ID );
INSERT INTO resource_item_business_function ( NULL, "Some Name", LAST_INSERT_ID() );
...etc...
INSERT INTO resource_item ( NULL, "Some Name", RESOURCE_ID );
INSERT INTO resource_item_business_function ( NULL, "Some Name", LAST_INSERT_ID() );

COMMIT;
Kevin Peno
Ugh. I was hoping there was some kind of clever scripting/looping I could do to avoid individual SQL statements. The other side of this is that there is no cascading of FKs, so I was hoping I could write the script to automagically delete existing records if executed multiple times. For clarity, I left that last part out. :-)
Rob Wilkerson
And then drop the procedures once the script completes its execution, I guess? I definitely don't want this kind of procedure to linger on the db.
Rob Wilkerson
If it is not an ongoing operation, I would not use database side SP's or triggers.
Kevin Peno
Yeah. This is, in theory, a one-time operation. The multiple executions represent the trial and error of the testing process.
Rob Wilkerson
Reading back on your first response. You will get errors generated by using the inserts above. Just replace `COMMIT;` with `ROLLBACK;` This will test your inserts within the transactiona nd revert before completion. All integrity checks are done within the transaction, so this should not affect your testing.
Kevin Peno