I have two tabels with a relation and I want to update a field in table A. Is it possible to combine update and join in the same query? I googled it but didnt find any working solution?
UPDATE md SET md.status = '3' FROM pd_mounting_details AS md LEFT OUTER JOIN pd_order_ecolid AS oe ON md.order_data = oe.id
I'm using MS SQL
SQL Server UPDATE JOIN syntax To query data from related tables, you often use the join clauses, either inner join or left join. In SQL Server, you can use these join clauses in the UPDATE statement to perform a cross-table update.
The most easiest and common way is to use join clause in the update statement and use multiple tables in the update statement. Here we can see that using join clause in update statement. We have merged two tables by the use of join clause.
A left outer join is a method of combining tables. The result includes unmatched rows from only the table that is specified before the LEFT OUTER JOIN clause. If you are joining two tables and want the result set to include unmatched rows from only one table, use a LEFT OUTER JOIN clause or a RIGHT OUTER JOIN clause.
In SQL Server, we can join two or more tables, but we cannot update the data of multiple tables in a single UPDATE statement.
Update t SET t.Column1=100 FROM myTableA t LEFT JOIN myTableB t2 ON t2.ID=t.ID
Replace myTableA
with your table name and replace Column1
with your column name.
After this simply LEFT JOIN to tableB. t
in this case is just an alias for myTableA
. t2
is an alias for your joined table, in my example that is myTableB
. If you don't like using t
or t2
use any alias name you prefer - it doesn't matter - I just happen to like using those.
If what you need is UPDATE from SELECT statement you can do something like this:
UPDATE suppliers SET city = (SELECT customers.city FROM customers WHERE customers.customer_name = suppliers.supplier_name)
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