Updating table based on a second query's result

-- -- 932 Reputation points
2023-01-23T04:24:33.71+00:00

Hi

I have a select query on a table. Based on if any rows are returned or not in the query how can I update a boolean column in a second table?

Thanks

Regards

Access
Access
A family of Microsoft relational database management systems designed for ease of use.
400 questions
Access Development
Access Development
Access: A family of Microsoft relational database management systems designed for ease of use.Development: The process of researching, productizing, and refining new or existing technologies.
882 questions
{count} votes

3 answers

Sort by: Most helpful
  1. Sreeju Nair 12,366 Reputation points
    2023-01-23T13:05:14.8333333+00:00

    You can use If Condition in SQL to wrap an insert statement inside the If statement. An example is given below.

    IF NOT EXISTS (SELECT 1 FROM myTable WHERE ID=25)
        INSERT INTO AnotherTable(column1, column2)
        VALUES(......)
    

  2. -- -- 932 Reputation points
    2023-01-25T11:34:36.95+00:00

    Hi

    Chat GPT gave me these solutions. Updating customer table based on if any orders exist in orders table for the customer.

    UPDATE Customers

    SET IsActive = IIF(DLookup("CustomerID", "Orders", "CustomerID=" & Customers.CustomerID) Is Not Null, True, False)

    OR

    UPDATE Customers

    SET IsActive = True

    FROM Customers

    LEFT JOIN Orders ON Customers.CustomerID=Orders.CustomerID

    WHERE Orders.CustomerID IS NOT NULL

    UPDATE Customers

    SET IsActive = False

    FROM Customers

    LEFT JOIN Orders ON Customers.CustomerID=Orders.CustomerID

    WHERE Orders.CustomerID IS NULL

    Thanks

    Regards

    0 comments No comments

  3. Ken Sheridan 2,841 Reputation points
    2023-01-25T17:55:14.09+00:00

    You can simplify that to:

    UPDATE Customers LEFT JOIN Orders

    On Customers.CustomerID = Orders.CustomerID

    SET IsActive = (Orders.CustomerID IS NOT NULL);

    Bear in mind that the inclusion of an IsActive column in the Customers table does introduce redundancy and the possibility of update anomalies. You can return the value with a query like this without the risk of inaccurate data:

    SELECT Customers.*, (Orders.CustomerID IS NOT NULL) As IsActive

    FROM Customers LEFT JOIN Orders

    On Customers.CustomerID = Orders.CustomerID;

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.