---
title: "合理利用DW完成PB的多表更新"
author: "Ben.Sin"
date: "2008-01-22T23:26:50Z"
tags: ["SQL", "工作"]
slug: "dw-pb"
draft: false
lastmod: "2008-01-22T23:26:50Z"
id: 177513
url: "https://ben-sin.iteye.com/blog/177513"
---

案例：有一个业务需要同时更新两个或以上的表  
分析：  
同时更新两个表，简单一点的就是用其中一个表做DW更新，同时用SQL更新另外一个表；或者页trigger实现其他表的更新。但这样对于相类似的业务就无疑是大大增加工作量。而且维护不方便。  
但我们细细考虑一下，DW作为PB的利器自然有他独到的地方。更新属性就好像是为了这种多表更新而设计的。  
PB更新数据库的时候首先看更新的table,然后看需要更新的column。也就是说，只需要在更新的时候设置好更新属性，就可以方便的实现多表更新了。  
步骤可以简单理解为：更新的时候将表1作为可更新表，表1的column作为可更新column。更新完后再设置表2作为可更新表，表2的column作为可更新column。

实例：  
假设有tabletbl\_1(col\_1, col\_2), tbl\_2(col\_1, col3)

那么，DW的SQL就是  
select  tbl\_1.col\_1,  
             tbl\_1.col\_2,  
             tbl\_2.col\_3  
   from tbl\_1, tbl\_2  
where tbl\_1.col\_1 = tbl\_2.col\_1

当DW作了一系列操作后，在更新的时候执行以下script

long ll\_cnt = 0  
int i = 0  
string ls\_table\[2] = {'tbl\_1', 'tbl\_2‘}  
string ls\_col  
string ls\_col\_dbname  
string ls\_update  
string ls\_updateable  
string ls\_error  
boolean lb\_update

// 循环table列表，实现多表更新  
for i = 1 to upperBound(ls\_table)  
    // 循环dw的column  
    for ll\_cnt = 1 to long(dw\_1.describe("DataWindow.Column.Count"))  
        ls\_col = dw\_1.describe("#" + string(ll\_cnt) + ".name")  
        ls\_col\_dbname = dw\_1.describe("#" + string(ll\_cnt) + ".dbname")  
         
        // 如果属于更新表的column或者key，设为可更新column  
        // 这里也可以将公共column也列作可更新column  
        if pos(ls\_col\_dbname, ls\_table + ".") = 1 or &  
                lower(dw\_1.describe("#" + string(ll\_cnt) + ".key")) = "yes" then  
            ls\_updateable = ".update=yes"  
        else  
            ls\_updateable = ".update=no"  
        end if  
         
        ls\_update += "~t" + ls\_col + ls\_updateable  
    next  
     
    // 设置更新table  
    ls\_update += "~tDataWindow.Table.UpdateTable='" + ls\_table\[i] + "'"  
     
    // 更新设置无误后update  
    ls\_error = dw\_1.modify(ls\_update)  
    if trim(ls\_error) &lt;&gt; '' or ls\_error &lt;&gt; '!' then  
        if dw\_1.update(true, false) = 1 then  
             lb\_update = true  
        else  
             lb\_update = false  
             // 退出for循环  
             exit  
        end if  
    end if

nex

// 此处根据更新情况提交事务  
if lb\_update then  
    commit;  
    // 重设dw状态  
    dw\_1.resetupdate()  
else  
    rollback;  
end if

//到这里就完成了多表更新了