sql server set命令,从另一个大表中查找

时间:2013-02-04 09:53:54

标签: sql-server set

这可能是一个简单的问题,但我对此很新。我正在尝试使用以下命令在SQL Server中设置列:

update myTable 
set myCol = a.col 
from table2 as a 
where a.col_1 = col_1 and a.col_2 = col_2;

myTable是一个大约1.5亿行。和table2约300,000行。我已正确索引table2,因此查找速度很快。我分别在一百万行上尝试了这个,花了大约20秒。但整个桌子花了很长时间,现在已经过了两天,但还没完成。我想知道是否有更好的解决方案。

提前致谢。

2 个答案:

答案 0 :(得分:1)

我认为UPDATE语句的语法应该是

UPDATE  b 
SET     b.myCol = a.col 
FROM    myTable b
        INNER JOIN table2 a
            ON  a.col_1 = b.col_1 AND
                a.col_2 = b.col_2

您需要在两个表格上提供化合物INDEX(col_1,col_2)。

答案 1 :(得分:0)

试试这个:

update myTable 
set myTable.myCol = (select a.col from table2 as a 
                     where a.col_1 = myTable.col_1 and 
                     a.col_2 = myTable.col_2
                    )

或者如果这不起作用,可能是因为加入条件的真正唯一性存在问题。

尝试改为:(这应该是快速的快速捕捉器......但证明您的数据很可能处于不一致的状态。)

update myTable 
set myTable.myCol = (select top 1 a.col from table2 as a 
                     where a.col_1 = myTable.col_1 and 
                     a.col_2 = myTable.col_2
                    )