Skip to content
Advertisement

How to update numerical column of one table based on matching string column from another table in SQL

I want to update numerical columns of one table based on matching string columns from another table.i.e., I have a table (let’s say table1) with 100 records containing 5 string (or text) columns and 10 numerical columns. Now I have another table that has the same structure (columns) and 20 records. In this, few records contain updated data of table1 i.e., numerical columns values are updated for these records and rest are new (both text and numerical columns).

I want to update numerical columns for records with the same text columns (in table1) and insert new data from table2 into table1 where text columns are also new.

I thought of taking an intersect of these two tables and then update but couldn’t figure out the logic as how can I update the numerical columns.

Note: I don’t have any primary or unique key columns.

Please help here. Thanks in advance.

Advertisement

Answer

The simplest solution would be to use two separate queries, such as:

UPDATE b
SET b.[NumericColumn] = a.[NumericColumn],
  etc...
FROM [dbo].[SourceTable] a
JOIN [dbo].[DestinationTable] b
  ON a.[StringColumn1] = b.[StringColumn1]
  AND a.[StringColumn2] = b.[StringColumn2] etc...

INSERT INTO [dbo].[DestinationTable] (
  [NumericColumn],
  [StringColumn1],
  [StringColumn2],
  etc...
)
SELECT a.[NumericColumn],
  a.[StringColumn1],
  a.[StringColumn2],
  etc...
FROM [dbo].[SourceTable] a
LEFT JOIN [dbo].[DestinationTable] b
  ON a.[StringColumn1] = b.[StringColumn1]
  AND a.[StringColumn2] = b.[StringColumn2] etc...
WHERE b.[NumericColumn] IS NULL
  --assumes that [NumericColumn] is non-nullable.
  --If there are no non-nullable columns then you
  --will have to structure your query differently

This will be effective if you are working with a small dataset that does not change very frequently and you are not worried about high contention.

There are still a number of issues with this approach – most notably what happens if either the source or destination table is accessed and/or modified while the update statement is running. Some of these issues can be worked around other ways but so much depends on the context of how the tables are used that it is difficult to provide a more effective generically-applicable solution.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement