I have 2 tables:
City table - columns CityID, Name, Period
Assets table - columns AssetID, Name
I have to update the Period column of the City table with AssetID of the Assets table matching with the top 1 where City.Name=Assets.Name. The Assets table have identical names for different assets.
Example Assets table:
AssetID Name
1 Asset1
2 Asset1
3 Asset2
4 Asset2
How can I do this? I tried with different queries but I am not able to get it.
UPDATE table SET col = ( SELECT other_col FROM other_table WHERE other_table. table_id = table.id ); Perhaps an easier way is to specify multiple tables after the UPDATE clause. Only the SET expression will perform updates but listing additional tables will allow the tables to be included.
The UPDATE statement in SQL is used to update the data of an existing table in database. We can update single columns as well as multiple columns using UPDATE statement as per our requirement. UPDATE table_name SET column1 = value1, column2 = value2,...
UPDATE City
SET Period = a.AssetID
FROM (SELECT TOP 1 AssetID, Name FROM Assets ORDER BY AssetID ASC) AS a
WHERE City.Name = a.Name;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With