TSQL转换select语句以使用连接进行更新

时间:2012-08-09 14:20:38

标签: select join

我有以下select语句:

SELECT  projectid,documentid,revisionno,configurationid,variable45,
        ISNULL(Variable45, (SELECT TOP 1 variable45 FROM pivot_table WHERE documentid = t.documentid and projectid=t.projectid
        and configurationid=t.configurationid and cast(revisionno as int) < cast(t.revisionno as int) AND Variable45 is NOT NULL 
        ORDER BY projectid desc,documentid desc ,revisionno desc,configurationid desc)) as NewCol
FROM    pivot_table t;

我尝试按以下方式转换为更新版本,但是我得到错误的记录更新。任何人都可以帮我解决我的问题:

UPdate PIVOT_TABLE
set variable45 = ((SELECT TOP 1 variable45 FROM pivot_table t WHERE t.documentid = documentid and t.projectid=projectid
        and t.configurationid=configurationid and cast(t.revisionno as int) < cast(revisionno as int) AND Variable45 is NOT NULL 
        ORDER BY revisionno desc)) where Variable45 is NULL;

DB:SQLExpress2008。

请指教。谢谢。

1 个答案:

答案 0 :(得分:0)

好的我明白了:

    UPdate pt
    set pt.variable45 = ((SELECT TOP 1 t.variable45 FROM pivot_table t WHERE 
t.documentid = pt.documentid and t.projectid=pt.projectid and t.configurationid=pt.configurationid and cast(t.revisionno as int) < cast(pt.revisionno as int) AND t.variable45 is NOT NULL 
            ORDER BY revisionno desc)) from PIVOT_TABLE pt where pt.variable45 is NULL;