[英]How to update SQL Server column after from different table
I have a table called TableA that stored list of event like this我有一个名为 TableA 的表,它存储了这样的事件列表
Event_Id Event_Name
1 Found in AD
2 Found in AAD
I have another table call Table B and it look something like this我有另一个表称为表 B,它看起来像这样
Event_Id UserName Extra
NULL David Found In AAD
1 James Found in AD
Null Ronal Null
I'm just trying to update only a missing/Null value in TableB Event_ID column based on comparing Table1 Event_Name and TableB Extra columns.我只是尝试根据比较 Table1 Event_Name和 TableB Extra列仅更新 TableB Event_ID列中的缺失值/空值。
I'm doing manually process like this for now so I would be really appreciated If I can get any help on how to join directly between the two table and update it.我现在正在做这样的手动处理,所以如果我能得到任何关于如何直接连接两个表并更新它的帮助,我将不胜感激。
Update Table B
Set Event_Id = case
when Extra = 'Found in AAD' then 2
end
You can use a simple sub-query in your UPDATE
to do that.您可以在
UPDATE
中使用一个简单的子查询来做到这一点。
UPDATE TableB SET
Event_Id = (SELECT Event_Id from TableA a where a.Event_Name = TableB.Extra)
WHERE Event_Id is null;
This will look for any matches on the Event_Name
and Extra_Name
and update the Extra
table's Event_Id
based on the match.这将查找
Event_Name
和Extra_Name
上的任何匹配项,并根据匹配项更新Extra
表的Event_Id
。
SQL: SQL:
UPDATE
Extra_Data
SET
Extra_Data.Event_Id = a.Event_Id
FROM
Event_Data a
INNER JOIN Extra_Data b ON a.Event_Name = b.Extra_Name
WHERE
b.Event_Id IS NULL;
Results:结果:
| Event_Id | UserName | Extra_Name |
|----------|----------|--------------|
| 2 | David | Found In AAD |
| 1 | James | Found in AD |
| (null) | Ronal | (null) |
SQL Fiddle: SQL 小提琴:
http://sqlfiddle.com/#!18/3a2ea/7 http://sqlfiddle.com/#!18/3a2ea/7
update table_b
set table_b.Event_Id = table_a.Event_Id
from table_b
JOIN table_a
ON table_b.extra = table_a.Event_Name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.