基于匹配另一个表中的2个字段来更新字段

时间:2013-10-11 09:53:56

标签: sql tsql sql-update

这是我的第一篇帖子,所以要温柔;)

我正在尝试根据Table1&中{2}列中2列的匹配数据更新Table 1列上的字段Table 2

列名是:

Table1.KeyField = Table2.KeyField
Table1.FieldName = Table2.FieldName

Table 1中要更新的列NumericValue为零。

我尝试过的每一种方式都会导致错误:

  

子查询返回的值超过1。这是不允许的   子查询跟随=,!=,<,< =,>,> =或当子查询用作   表达。

任何帮助表示感谢。

由于

2 个答案:

答案 0 :(得分:1)

update t
set    t.NumericValue = ???
from   Table1 t
join   Table2 t2
on     t.KeyField = t2.KeyField
and    t.FieldName = t2.FieldName

答案 1 :(得分:1)

示例数据:

create table Table1 (KeyField int,FieldName varchar(20),Targetcolumntoupdate numeric(5,2));
create table Table2 (KeyField int,FieldName varchar(20),Sourcecolumntoupdate numeric(5,2));
insert into Table1 values  (1,'F1',0.00);
insert into Table1 values  (2,'F1',0.00);
insert into Table2 values  (1,'F1',1.00);
insert into Table2 values  (1,'F1',2.00);

您是否要将Table1中的列更新为:

-- Wrong approach possible cause of error stated
Update Table1
Set Table1.Targetcolumntoupdate = 
( SELECT (T2.Sourcecolumntoupdate)
FROM Table1 T1 
INNER JOIN Table2 T2 ON
T1.KeyField = T2.KeyField AND T1.FieldName = T2.FieldName) ; 

然后它是错误的,因为您可以看到您创建的子查询以选择更新所需的数据Targetcolumntoupdate将返回多个可能的值。

正确查询如下:

Update T1
Set T1.Targetcolumntoupdate = (T2.Sourcecolumntoupdate)
FROM Table1 T1 
INNER JOIN Table2 T2 ON
T1.KeyField = T2.KeyField AND T1.FieldName = T2.FieldName;

希望这有帮助!!!

相关问题