![](/img/trans.png)
[英]SQL Server: update value of a column in one table based on the matching value of another column in the same table to another table's column
[英]How to update numerical column of one table based on matching string column from another table in SQL
我想根據來自另一個表的匹配字符串列更新一個表的數字列。即,我有一個表(比如說 table1),其中包含 100 條記錄,其中包含 5 個字符串(或文本)列和 10 個數字列。 現在我有另一個具有相同結構(列)和 20 條記錄的表。 在此,很少有記錄包含 table1 的更新數據,即這些記錄的數值列值已更新,rest 是新的(文本和數值列)。
我想更新具有相同文本列(在 table1 中)的記錄的數字列,並將 table2 中的新數據插入到 table1 中,其中文本列也是新的。
我想取這兩個表的交集然后更新,但無法弄清楚如何更新數字列的邏輯。
注意:我沒有任何主鍵或唯一鍵列。
請在這里幫忙。 提前致謝。
最簡單的解決方案是使用兩個單獨的查詢,例如:
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
如果您正在處理一個不經常更改並且您不擔心高爭用的小型數據集,這將是有效的。
這種方法仍然存在許多問題 - 最明顯的是如果在更新語句運行時訪問和/或修改源表或目標表會發生什么。 其中一些問題可以通過其他方式解決,但很大程度上取決於表格使用方式的上下文,因此很難提供更有效的通用解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.