Home  Fees/Services  Access Examples  Tutorials  Access Download  Articles  Search  Contact  Privacy  Links

Access Query Examples
Set Master Record Field From Detail Record Values

Update Parent Record Based on Child Record Fields SQL Queries

Access Database Tutorials>SQL Queries>Master/Detail Record Updates

Download Access Program


Aggregate Functions
Child/Parent Table Query
Choose Function
SQL Choose Function +
Crosstab/Pivot Query
SQL Crosstab Query +
DateTime Query
SQL Delete Query
External Link to Tables
Filter Report Records
Group By Clause
Having Clause Query
Histogram Query
Insert Into Query/Append
Master/Detail Updates
SQL Order By Dynamic
Parameter Query
SQL Predicate Example
Self Join Query
Access Scalar Query
Select Statement
Select Top 1 Query
Union Query Example
Update Query Example


Update Master Record Based on Detail Records

Bottom-up Query Examples - Detail Record Criteria Selects Master Records

In this example let us assume we have two tables in a master/detail relationship.  The main table contains Tasks which much be completed.

The detail table contains one or more Action Items for each task.   The two tables are linked by Task_ID.  All Action Items must be completed before the Task is complete.  We want to mark the task as done when all the action items have been completed.  We have an AfterUpdate trigger associated with the Completed field in the Action Items form.  Here is the code to update the master table (Tasks) when all items are completed for the task.

Private Sub Action_Complete_AfterUpdate()

    If Me.Action_Complete=true then

        DoCmd.RunSQL ("Update Tasks set Task_Complete=True " & _
        " Where Tasks.Task_ID in " & _
        " (Select Task_ID from Action_Items where Task_ID=" & Me.Task_ID & _
        " Having Max(Action_Items.Action_Completed)=-1 " & _
        " Group By Task_ID)")

    Else

        DoCmd.RunSql ("Update Tasks set Task_Complete=False " & _
        " where Task_ID=" & Me.Task_ID)

    End If

End Sub

Ok... this is more of an SQL example than a visual basic example.  But this is a perfect example of creating a very simple solution to a potentially very complicated task.   The key to creating highly maintainable Access databases is to have a consultant who knows both SQL programming and visual basic programming.

Here is the trick to this query... If all the Action_Completed Yes/No fields are true (-1) then the Max of them will be -1.  If any are not true (0) then the Max will be 0.

You should have indexes on all table fields mentioned in the SQL statement.




 

We now offer web-based SQL/Server application development in partnership with Integrated Databases, Inc. (new projects only).



Contact Information

SQL Queries
MS Access SQL Queries 2007 2003 2000  All Windows Versions