使用映射表更新基于其他两个值的值

问题描述:

我有两个表;一个很少更新的查找表,以及一个频繁更新的数据表。使用映射表更新基于其他两个值的值

查找表看起来像这样,Code1和Code2的组合对每一行都是唯一的。

Code1 | Code2 | Classification 
------------------------------ 
AB | CD | Class1 
XX | YY | Class2 

数据表看起来像这样;

SomeData | Code1 | Code2 | Classification 
------------------------------ 
foo  |AB  | CD | 
bar  |XX  | YY | 

我需要动态更新数据表的分类对应于查找表中Code1和Code2的唯一组合。

实现此目的最简单/最优雅的方式是什么?

+1

为什么?只需使用'JOIN'来获取需要它们的值。 –

您可以更新2台这样的

UPDATE table1, table2 
SET table2.Classification = table1.Classification 
WHERE table1.Code2 = table2.Code2 AND table1.Code1 = table2.Code1; 
+1

需要做一个轻微的mod来使这个工作在t-sql中; 的begin tran UPDATE table1的 SET table2.Classification = table1.Classification FROM表1,表2 WHERE table1.Code2 = table2.Code2 AND table1.Code1 = table2.Code1 提交TRAN – cc0

您只需加入2个表所示:

Select b.SomeData, b.Code1, b.Code2, a.Classification 
FROM 
Lookup_table a 
left join 
Data_table b 
on (a.Code1 = b.Code1 and a.Code2 = b.Code2) 

所以您的更新变为:

Update b 
Set b.Classification = a.Classification 
FROM 
Data_table b 
Right join 
Lookup_table a 
on (a.Code1 = b.Code1 and a.Code2 = b.Code2) 

你可以只创建视图与此代码,并得到whenver你想

select t2.somedata,t1.Code1,t1.Code2,t1.Classification from lookup_table as t1 
left join data_table as t2 on t1.code1=t2.code1 and t1.code2=t2.code2 

如果您仍然需要更新,请使用这个

update t2 
set 
t2.Classification=t2.Classification 
from lookup_table as t1 
inner join data_table as t2 on t1.code1=t2.code1 and t1.code2=t2.code2