I have an MS Access application running on Microsoft SQL Server. I have some VBA automation that manipulates the database.
My example: Shipping Orders (tblSalesOrders)
When I click "Ship Order", there are some validation checks and if everything passes, I want to create a Shipment (tblShipments) and Shipment Items (tblShipmentDetails). Let's not dig to deep into my design, I want to keep this quite generic if possible.
Of course I want to use SQL Transactions to ensure data integrity.
This is my VBA Code (Conn is my ADO Connection, Exec is my custom built function to execute SQL command within Conn):
intSalesOrderID = Forms!frmSalesOrderDetails!SalesOrderID
Conn.BeginTrans
Exec "INSERT INTO tbl1Shipments (CustomerID, DateShipped) " & _
"VALUES (" & DLookup("CustomerID", "dbo_tbl1SalesOrders", "SalesOrderID=" & intSalesOrderID) & ", " & _
"GETDATE())"
intShipmentID = DMax("ShipmentID", "dbo_tbl1Shipments", "CustomerID=" & DLookup("CustomerID", "dbo_tbl1SalesOrders", "SalesOrderID=" & intSalesOrderID))
Exec "INSERT INTO tbl1ShipmentDetails (ShipmentID, ---RandomColumn1---, ---RandomColumn2)"
"VALUES (" & intShipmentID & ", " & _
GetRandomColumn1Somewhere,
GetRandomColumn2Somewhere)
Conn.CommitTrans
The problem is that I need to extract the ShipmentID from the previously created Shipment, so I can assign the Foreign Key to Shipment Details. My best idea so far was to use DMAX using the CustomerID as a parameter, but that's probably a bad thing to do...
It doesn't work anyway because I'm still inside the transaction and the Shipment hasn't been truly created yet.
My question is - how to do this correctly? Thanks a lot in advance.
Tomas