I'm using MS SQL Server. I have 2 tables:
Table1 stores information about the individual object number (Object_id), the number of its property (Prop_id) and the value of this property (Value).
Example
| Object_id | Prop_id | Value |
|---|---|---|
| 1 | 55 | 980 |
| 1 | 76 | |
| 2 | 55 | 970 |
| 2 | 76 | |
| 3 | 55 | 960 |
| 3 | 76 |
Table 2 contains the values of the object properties:
| NUM | Name |
|---|---|
| 980 | ABC |
| 970 | DEF |
| 960 | HIJ |
I need to update table 1 with values from table 2. I need to put "Name" in the "Value" column for a property with index 76. The connection of the two tables should be by the fields "Value" for property 55 in Table 1 and "Num" in Table 2.
In the end, I want to get this:
| Object_id | Prop_id | Value |
|---|---|---|
| 1 | 55 | 980 |
| 1 | 76 | ABC |
| 2 | 55 | 970 |
| 2 | 76 | DEF |
| 3 | 55 | 960 |
| 3 | 76 | HIJ |
Please help me write a query that will give the desired result!
I have already tried several SQL queries, but they either do not update the table at all, or substitute only the first value from the data sample.
My attempt:
UPDATE Table1
SET Table1.Value = name1.name
FROM (SELECT Table2.name
FROM Table1
JOIN Table2 ON Table2.num = Table1.Value
AND Table1.Prop_id = 55) AS name1
WHERE Table1.Prop_id = 76
This attempt updates the values in the table, but inserts only the first value from the SELECT query into all rows (i.e. the ABC value in all rows with property 76).
It is easier if you write the query step by step
First, you need to get the value from Table2 link to Table1
You will get the
Object_idwith the associateNamevalue fromTable2Next, you join it back to
Table1for updateVerify the result is what you want, just change the query to a
updatequeryAnd you will get the result you want in
Table1