表2中包含条件的SQL Server更新表1

时间:2016-12-08 11:37:22

标签: sql sql-server

我想用简单的case语句更新表中的字段。但是,我只想将此case语句应用于选定的行数。我确定这些行的唯一方法是连接另一个表,然后根据第二个表中的字段设置一些条件。

例如,这就是我认为它会起作用的方式......

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

但是,似乎没有像这样的更新语句内部的连接。至少不在MS SQL中。

我已经尝试过搜索答案,但我能找到的是人们试图用另一个表中的数据更新表,包括连接,其中一个人会在我的连接中放置一个“from”语句,然后是一个嵌套的select语句在里面加入。我不确定这对我来说是一个解决方案。我不想从另一个表更新,我想根据另一个表进行过滤。

我现在能想到的唯一解决方案是两个查询解决方案,首先检索obj_id的列表,然后在第二个更新语句中仅选择这些ID。不理想。

3 个答案:

答案 0 :(得分:3)

我们可以在SQL Server的UPDATE语句中使用JOIN

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

答案 1 :(得分:2)

你可以。语法需要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');

答案 2 :(得分:2)

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