I have records in 3 tables that are related to each other. I am trying to copy the record to give the user a starting point for completing the form rather than starting from scratch. I have a stored procedure that works somewhat.
The top level record can have many related records in the middle level. I can copy the top level record no problem and retrieve the ID of the new record. I can also copy the middle level records and add it to the table using the new ID from the first step. The problem is that the middle level records also have many records in the third level. I don't know how to copy the third level records into each of middle level record it belongs to. I get the new ID from the middle step but it goes to the last record that was inserted so all of the third level records get put under that ID. I think the last step should be a subquery in the middle step? Here is what I have so far and thank you to anyone that can help.
ALTER PROCEDURE [dbo].[qryCopyQuote]
-- Add the parameters for the stored procedure here
@OriginalQuoteID INT,
@NewQuoteNumber VARCHAR(10),
@NewQuoteID INT OUTPUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
INSERT INTO [tbl_QuoteDetails](
[QuoteNumber], [Revision], [CurrentDate],
[QuoteDate], [Country], [StateID], [City],
[ProjectName], [RepCompanyID], [ApplicationEngineer],
[ElectricalEngineer], [MechanicalEngineer], [RevisionNotes]
)
SELECT @NewQuoteNumber, '-', [CurrentDate],
[QuoteDate], [Country], [StateID], [City],
[ProjectName], [RepCompanyID], [ApplicationEngineer],
[ElectricalEngineer], [MechanicalEngineer], [RevisionNotes]
FROM [tbl_QuoteDetails] AS QD
WHERE [QD].QuoteID = @OriginalQuoteID
SET @NewQuoteID = SCOPE_IDENTITY();
INSERT INTO [tbl_QuoteAssemblies](
[QuoteID], [AssemblyName], [AssemblyQuantity]
)
SELECT @NewQuoteID, [QA].[AssemblyName], [QA].[AssemblyQuantity]
FROM [tbl_QuoteAssemblies] AS QA
WHERE [QA].[QuoteID] = @OriginalQuoteID
DECLARE @NewAssemblyID int
SET @NewAssemblyID = SCOPE_IDENTITY();
INSERT INTO [tbl_QuoteAssemblyDetails](
[AssemblyID], [ItemQuantity], [PartNumber],
[ItemCost], [ItemDescription], [LastUpdate],
[VendorContractPrice], [VendorItem]
)
SELECT @NewAssemblyID, [QD].[ItemQuantity], [QD].[PartNumber],
[QD].[ItemCost], [QD].[ItemDescription], [QD].[LastUpdate],
[QD].[VendorContractPrice], [QD].[VendorItem]
FROM [tbl_QuoteAssemblyDetails] AS QD
INNER JOIN [tbl_QuoteAssemblies] QA ON [QD].[AssemblyID] = [QA].[AssemblyID]
WHERE [QA].[QuoteID] = @OriginalQuoteID
RETURN @NewQuoteID;