1

我有两个表,Table1 和 Table2。这些表之间的公共列是 CustId。表 1 包含一个 CustId 的多条记录,而作为主表的 table2 仅包含一条 Custid 记录以及所有相关的客户信息。

我想要做的是,用 table1 的最新修改记录更新 table2。

由于主表中有多个记录,我希望查询循环运行。

我写了以下内容,

update Table1 
set 
Table1.col1=b.col1,
Table1.col2 = b.col2,
Table1.col3 = case
 when b.col3 = (select Id from table4 where  name = 'Not Listed')
 then b.col4
 else b.col3
 end, 
Table1.col4 = case
 when b.col5 in (select Id from table5 where name = 'Not Listed')
 then b.col6
 else b.col5
 end
from 
    (select top 1 Table2.* 
    from Table2,Table1 where 
    Table2.CustId = Table1.CustId
    Order by 
    Table2.modifiedon desc )b

where Table1.CustId = b.CustId

但我不确定它是否会针对 table2 中的所有记录运行。

请帮助

4

1 回答 1

0

请尝试使用内部联接进行更新。有关详细信息,请参阅链接Mastering the SQL UPDATE Syntax

UPDATE T1
SET T1.col1=b.col1,
    T1.col2 = b.col2,
    T1.col3 = (case when b.col3 = (select Id from table4 where  name = 'Not Listed')
            then b.col4
            else b.col3 end),
    T1.col4 = (case when b.col5 = (select Id from table5 where name = 'Not Listed')
            then b.col6
            else b.col5 end)

FROM Table1 T1 INNER JOIN 
(
    select ROW_NUMBER() over(partition by CustId order by modifiedon desc) Rnum,
        CustId, modifiedon, col1, col2, col3, col4, col5, col6
    FROM Table2

)x ON x.CustId=T1.CustId
WHERE x.Rnum=1
于 2013-01-24T10:35:56.953 回答