I have two tables
Table A
Number
111
222
333
444
Table B
Number Another
111 AAA
222 BBB
666 CCC
777 DDD
What I am would like to do, is apply an UPDATE statement conditional on whether the "Number" value in Table B exist in Table A. So the table would end up looking something like this.
Number Another
111 ZZZ
222 ZZZ
666 CCC
777 DDD
I know I need to use an UPDATE query and probably some kind of JOIN, but I am not sure on the syntax.
Any help greatly appreciated.
We can update the table using UPDATE statement in SQL. The update statement is always followed by the SET command. The SET command is used to specify which columns and values need to be updated in a table.
The SQL Server (Transact-SQL) EXISTS condition is used in combination with a subquery and is considered to be met if the subquery returns at least one row. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.
In such a case, you can use the following UPDATE statement syntax to update column from one table, based on value of another table. UPDATE first_table, second_table SET first_table. column1 = second_table. column2 WHERE first_table.id = second_table.
Yes. You need to update using a join like this:
update t2
set t2.Another = 'ZZZ'
from table1 t1
join table2 t2 on t1.Number = t2.Number
You can use exists
also.
Query
update t1
set t1.[Another] = 'ZZZ'
from [TableB] t1
where exists(
select 1 from [TableA] t2
where t1.[Number] = t2.[Number]
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With