简体   繁体   中英

SQL Server Update Table 1 with Condition in Table 2

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.

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')

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');
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');

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM