SQL Server更新从另一个表获取id

时间:2014-04-09 15:40:46

标签: sql sql-server sql-server-2008

我必须更新表中的某些行,但我需要从另一个表中获取引用ID。表结构类似于以下内容:

CoInvDept
+--------------+--------+--------+
| coinvdeptid  | coinv  | code   |
+--------------+--------+--------+

Coinv
+--------------+-------------+
| coinv        | itemnumber  | 
+--------------+-------------+

我需要更新代码,但我有itemnumber。我正在使用SQL SERVER 2008。 到目前为止

UPDATE coinvdept 
SET code = 'ABC123'
WHERE (SELECT coinvid WHERE itemnumber = '12345678')

3 个答案:

答案 0 :(得分:0)

我认为这就是你所追求的目标:

UPDATE coinvdept 
SET code = 'ABC123'
WHERE coinv IN (SELECT coinvid FROM coinv WHERE itemnumber = '12345678')

答案 1 :(得分:0)

UPDATE coinvdept 
SET code = 'ABC123'
WHERE coinv  = (SELECT coinvid FROM coinv WHERE itemnumber = '12345678')

OR

UPDATE T1

SET code='ABC123'

FROM coinvdept as T1
INNER JOIN Coinv as T2 ON T1.coinv=T2.coinv

AND T2.itemnumber='12345678'

两者都应该有效:)

答案 2 :(得分:0)

您可以使用in运算符将值与子查询结果进行匹配,并且子查询中需要from子句:

update
  coinvdept 
set
  code = 'ABC123'
where
  coinv in (select coinv from coinv where itemnumber = '12345678')

您还可以使用加入:

update
  d
set
  code = 'ABC123'
from
  coinvdept d
  inner join coinv c on c.coinv = d.coinv
where
  c.itemnumber = '12345678'

注意:我在查询中使用了字段名称coinv,而不是您在查询中使用的coinvid,因为这是您在表格结构中指定的内容。