简体   繁体   English

如何根据 SQL 中另一表的匹配字符串列更新一个表的数字列

[英]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.ie, I have a table (let's say table1) with 100 records containing 5 string (or text) columns and 10 numerical columns.我想根据来自另一个表的匹配字符串列更新一个表的数字列。即,我有一个表(比如说 table1),其中包含 100 条记录,其中包含 5 个字符串(或文本)列和 10 个数字列。 Now I have another table that has the same structure (columns) and 20 records.现在我有另一个具有相同结构(列)和 20 条记录的表。 In this, few records contain updated data of table1 ie, numerical columns values are updated for these records and rest are new (both text and numerical columns).在此,很少有记录包含 table1 的更新数据,即这些记录的数值列值已更新,rest 是新的(文本和数值列)。

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.我想更新具有相同文本列(在 table1 中)的记录的数字列,并将 table2 中的新数据插入到 table1 中,其中文本列也是新的。

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.提前致谢。

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.其中一些问题可以通过其他方式解决,但很大程度上取决于表格使用方式的上下文,因此很难提供更有效的通用解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM