Reputation: 2486
I want to update a field in a table with a simple case statement. However, I only want to apply this case statement to a select number of rows. The only way for me to determine what these rows are is to join on another table and then have some conditions based on the fields in that second table.
For example, this is how I thought it would work...
update table1
set table1.field1 = case
when table1.field1 = 'foo' then 'bar'
else 'foobar'
end
join table2 on table1.obj_id=table2.id
where table2.field1 = 'fizzbuzz'
and table2.field2 in ('foo', 'bar', 'foobar')
However, it seems that one cannot have a join inside the update statement like this. At least not in MS SQL.
I have tried searching for an answer but all I can find is people trying to update a table with data from another table including a join, whereby one would put a "from" statement where my join is and then a nested select statement with a join inside that. I am not sure this is a solution for me. I don't want to update from another table, I want to filter based upon another table.
The only solution I can think of now is a two query solution by first retrieving a list of obj_id
s and then selecting only these ids in a second update statement. Not ideal.
Upvotes: 1
Views: 673
Reputation: 3797
We can use JOIN in UPDATE statement in SQL Server
update t1
set t1.field1 = case
when t1.field1 = 'foo' then 'bar'
else 'foobar'
end
from table1 t1
inner join table2 on t1.obj_id=table2.id
where table2.field1 = 'fizzbuzz'
and table2.field2 in ('foo', 'bar')
Upvotes: 3
Reputation: 3127
update t1
set field1 = case
when t1.field1 = 'foo' then 'bar'
else 'foobar'
end
from table1 t1
join table2 t2 on t1.obj_id=t2.id
where t2.field1 = 'fizzbuzz'
and t2.field2 in ('foo', 'bar', 'foobar');
Upvotes: 2
Reputation: 1269883
You can. The syntax requires from
:
update t1
set field1 = (case when t1.field1 = 'foo' then 'bar' else 'foobar' end)
from table1 t1 join
table2 t2
on t1.obj_id = t2.id
where t2.field1 = 'fizzbuzz' and
t2.field2 in ('foo', 'bar', 'foobar');
Upvotes: 2