我有兩個表(A和B)。我想用表B的值col3_B更新col3_A。Col3_B的值是按順序排列的。所以Col3_A必須按照col3_B的順序更新。如何在表互不相關時從另一個表中依次更新表列的值
表A:
+--------+--------+--------+
| col1_A | col2_A | col3_A |
+--------+--------+--------+
| A | 1 | 5 |
| B | 1 | 3 |
| C | 1 | 2 |
| D | 1 | 1 |
+--------+--------+--------+
表B:
+--------+
| col3_B |
+--------+
| 6 |
| 7 |
| 8 |
| 9 |
+--------+
所需的結果:
+--------+--------+--------+
| col1_A | col2_A | col3_A |
+--------+--------+--------+
| A | 1 | 6 |
| B | 1 | 7 |
| C | 1 | 8 |
| D | 1 | 9 |
+--------+--------+--------+
問題我的代碼只設置從col3_B前兩個值都col3_A列,只有兩個值重複如
+--------+
| Col3_A |
+--------+
| 6 |
| 7 |
| 6 |
| 7 |
+--------+
我的代碼:
update A
set A.col2_A = '1', A.col3_A = B.col3_B
from (select ROW_NUMBER() OVER (ORDER BY [col] ASC) AS col3_B
from tableb) B
where A.col1_A in
(
'A',
'B',
'C',
'D'
)
order by如果記錄沒有排序,col2_a和col3_b的排序可能會成爲問題。我更喜歡上面的解決方案,其中您創建了副本並更新了副本。通過這種方式,我們可以測試副本表並確保更新是正確的,然後將其推送到主表 – Aparna