Search code examples
sqlms-accessvbams-access-2016

Insert Into where not exists from specific category


I have a table that contains several repair categories, and items that are associated with each repair category. I am trying to insert all the standard items from a specific repair category that don't already exist into a Details table.

TblEstimateDetails is a join table for an Estimate Table and StandardItem Table. And TblCategoryItems is a join table for the Repair Categories and their respective Standard Items.

For example in the attached image, Left side are all the Standard Items in a Repair Category, and Right side are all the Standard Items that are already in the EstimateDetails table.

Standard Items All vs Already Included

I need to be able to insert the 6 missing GUIDS from the left, and into the table on the right, and only for a specific estimate GID.

This is being used in an Access VBA script, which I will translate into the appropriate code once I get the sql syntax correct.

Thank you!

INSERT INTO TblEstimateDetails(estimate_GID, standard_item_GID)
SELECT 
 '55DEEE29-7B79-4830-909C-E59E831F4297' AS estimate_GID
 , standard_item_GID 
FROM TblCategoryItems 
WHERE repair_category_GID = '32A8AE6D-A512-4868-8E1A-EF0357AB100E'
AND NOT EXISTS 
  (SELECT standard_item_GID
  FROM TblEstimateDetails 
  WHERE estimate_GID = '55DEEE29-7B79-4830-909C-E59E831F4297');

Solution

  • Got it figured out. Access needs the subquery to be correlated to main query to work. So I set the WHERE clause in the subquery to equal the matching column in the main query. And I had to join the Estimates table so that it picked only the items in a specific estimate.

    SELECT 
     '06A2E0A9-9AE5-4073-A856-1CCE6D9C48BB' AS estimate_GID
     , CI.standard_item_GID 
    FROM TblCategoryItems CI 
    INNER JOIN TblEstimates E ON CI.repair_category_GID=E.repair_category_GID
    WHERE E.repair_category_GID = '15238097-305E-4456-B86F-3787C9B8219B' 
    AND NOT EXISTS 
      (SELECT ED.standard_item_GID 
      FROM TblEstimateDetails ED 
      WHERE E.estimate_GID=ED.estimate_GID
    );