I need to update a table column in SQL Server 2008 R2. The update depends on the two columns in another table.
Table1:
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:
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:
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. It means that id1 and id2 combination is not available for column "name" = "ac" in table2.
One way to check if a matching column exists in another table is to use EXISTS()
function.
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.
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 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):
update table1
set value=0
where value is null
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.