Reputation: 57
The first table consists of Accounts with State and Country information which are mostly correct with few wrong rows:
ID Account State Country Text
1001 Acc1 NJ USA
1002 Acc2 NY Null
1003 Acc3 Texas Japan
And I have the second table which has the correct state and Country information to which the first tables needs to be compared to:
ID State Country
1 NJ USA
2 NY USA
3 Texas USA
The query should check:
If both the above conditions are satisfied, the first table's Text column should get updated with the state value. If any of the two conditions are not satisfied, the text column should remain blank.So the result should look like this:
ID Account State Country Text
1001 Acc1 NJ USA NJ
1002 Acc2 NY USA
1003 Acc3 Texas USA
I am able to check whether both the conditions are satisfied, also I am able to get the rows which doesn't satisfy the condition. However, I am not sure how to go forward and update the table with the correct state. Any help would very much appreciated.
Upvotes: 1
Views: 1832
Reputation: 13393
You can try this.
UPDATE T1
SET
[Text] = (CASE WHEN T1.Country = T2.Country THEN T1.[State] ELSE NULL END)
, Country = (CASE WHEN T1.Country = T2.Country THEN T1.Country ELSE T2.Country END)
FROM TableAccounts T1
INNER JOIN TableCountry T2 ON T1.[State] = T2.[State]
Upvotes: 3
Reputation: 322
These queries will work with MSSQL to drive an update in either direction...
SELECT State, Country FROM t1
EXCEPT
SELECT State, Country FROM t2
SELECT State, Country FROM t2
EXCEPT
SELECT State, Country FROM t1
t1 is this in your post: (ID,Account,State,Country,Text)
t2 is this in your post: (ID,State,Country)
Upvotes: 4