[英]Update a table based on if two column values appear in another table on SQL Server 2008 R2
I need to update a table column in SQL Server 2008 R2. 我需要更新SQL Server 2008 R2中的表列。 The update depends on the two columns in another table.
更新取决于另一个表中的两列。
Table1: 表格1:
id1 (varchar(20)) id2 (varchar(20)) value (bit) name_without_this_id1_id2
--------------------------------------------------------------------------
58 669 null null
188 875 null null
87 30 null null
Table 2: 表2:
id0 (int) id1 (varchar(20)) id2 (varchar(20)) name(varchar(10))
---------------------------------------------------------------
1 58 669 ab
2 87 30 ac
3 58 669 ab
After update table 1, I can get: 更新表1之后,我可以获得:
id1 (varchar(20)) id2 (varchar(20)) value (bit) name_without_this_id1_id2
--------------------------------------------------------------------------
58 669 1 ac
188 875 0 ab,ac
87 30 1 ab
About "name_without_this_id1_id2", if the combination of id1 and id2 are not available in table2's id1 and id2, the column "name"'s value in table2 needs to be added to the column "name_without_this_id1_id2" in table1. 关于“ name_without_this_id1_id2”,如果在表2的id1和id2中id1和id2的组合不可用,则需要将表2中“名称”列的值添加到表1的“ name_without_this_id1_id2”列中。 It means that id1 and id2 combination is not available for column "name" = "ac" in table2.
这意味着id1和id2组合不适用于表2中的“名称” =“ ac”列。
One way to check if a matching column exists in another table is to use EXISTS()
function. 检查另一个表中是否存在匹配列的一种方法是使用
EXISTS()
函数。
Below code should work 下面的代码应该工作
update table1 set value = 1
where exists( select 1 from table2 where table1.id1 = table2.id1 );
This function returns TRUE
if subquery returns any rows. 如果子查询返回任何行,则此函数返回
TRUE
。
You can use a join within update command to update all ids which exists in table2 (you can also use exists
instead of join): 您可以在update命令中使用join来更新table2中存在的所有ID(也可以使用
exists
代替join):
update table1
set value= 1
from table1 join table2 on table1.id1=table2.id1 and table1.id2=table2.id2
and finally set the null values to 0 (ids they are not in table2): 最后将null值设置为0(ids不在table2中):
update table1
set value=0
where value is null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.