Reputation: 3
I'm trying to update my parent table column if my child table column has all the same values for a single ParentId.
T1 - Parent
| ParentId | StatusId |
|---------------------|------------------|
| 1 | 1 |
|---------------------|------------------|
| 2 | 1 |
|---------------------|------------------|
T2 - Child
| ChildId | ParentId | StatusId |
|---------------------|------------------|------------------|
| 1 | 1 | 0 |
|---------------------|------------------|------------------|
| 2 | 1 | 0 |
|---------------------|------------------|------------------|
| 3 | 1 | 0 |
|---------------------|------------------|------------------|
| 4 | 2 | 1 |
|---------------------|------------------|------------------|
| 5 | 2 | 0 |
|---------------------|------------------|------------------|
If T2 status column has all 0's for ParentId 1 then set status in T1 to 0 else if there is a 1 status for any ParentId in T2 then set the status in T1 to 1 or do nothing.
Desired Result after update statement:
T1 - Parent
| ParentId | StatusId |
|---------------------|------------------|
| 1 | 0 |
|---------------------|------------------|
| 2 | 1 |
|---------------------|------------------|
T2 - Child
| ChildId | ParentId | StatusId |
|---------------------|------------------|------------------|
| 1 | 1 | 0 |
|---------------------|------------------|------------------|
| 2 | 1 | 0 |
|---------------------|------------------|------------------|
| 3 | 1 | 0 |
|---------------------|------------------|------------------|
| 4 | 2 | 1 |
|---------------------|------------------|------------------|
| 5 | 2 | 0 |
|---------------------|------------------|------------------|
I know can perhaps do something like this using an update and maybe a while loop but I'm not quite sure how to construct it. Any help is appreciated.
Upvotes: 0
Views: 54
Reputation: 1112
This can be done using an Update From Select
Update T1
Set StatusID = newStatusID
From
(
Select ParentID as changedParentID
, max(StatusID) as newStatusID
From T2
Group By ParentID
)x
Where T1.ParentID = x.changedParentID
And T1.StatusID <> x.newStatusID
Upvotes: 1