I have two tables with a classic parent-child foreign key relation.They both have an 'Active' column.I want to update the active column of the parent table and set it to true if at least one of its child records is set to active otherwise it should be updated to false.I've managed getting the result with the following. First setting all parent active columns to false. And a second update statement to set it to true if at least one child is set to active.My question is if there is a better way (for example using only one update statement).
declare @parent table(ID int, Active bit)declare @child table(ID int, FKParent int, Active bit)insert into @parentvalues(1,0),(2,1),(3,1)insert into @childvalues(1,1,0),(2,1,1),(3,1,0),(4,2,0),(5,2,1),(6,3,0),(7,3,0)select *from @parentselect *from @childupdate pset p.Active = 0from @parent as pupdate pset p.Active = 1from @parent as pwhere exists( select distinct c.FKParent from @child as c where c.FKParent = p.ID and c.Active = 1)select *from @parent