基于DB2V5R4M0中的另一个表更新多个列



我正在为AS400 DB/2表编写更新语句。它需要使用另一个具有匹配字段的表中的数据更新多行。我们的驱动程序显示版本是:05.04.0000 OS/400 V5R4M0

我很难弄清楚要使用的正确语法。

以下是我用来收集正确数据的基本CTE:

with tablesql as
(
select *
from TBL1CPY
),
tableAS400 as 
(
select *
from TBL1 
where LDT = '20220104' AND US ='ADMIN'
),
tableSQLFrmJoin as
(
select s.* 
from tablesql s, tableAS400 a
where s.prj = a.prj AND s.PN = a.PN AND s.IN = a.IN
)

以下是我在CTE上尝试过的一些不同的东西:

1)  update TBL1 t1
set (STS) = ( select STS from  tableSQLFrmJoin ) t2
where t1.prj = t2.prj AND t1.PN = t2.PN AND t1.IN = t2.IN 
*this throws the error: Error Source: IBMDA400 Command, Error Message: SQL0199: Keyword Update  not expected...* 
2) MERGE INTO TBL1 t1
USING 
(select * from tableSQLFrmJoin) t2
on (t1.prj = t2.prj AND t1.PN = t2.PN AND t1.IN = t2.IN) 
when matched then
update SET STS = 'TST'
*this throws the error: Error Source: IBMDA400 Command, Error Message: SQL0104: Token MERGE  not expected...* 
3) update tbl1 t1, tableSQLFrmJoin t2
set t1.STS = 'tst'
where t1.prj = t2.prj AND t1.PN = t2.PN AND t1.IN = t2.IN 
*this throws the error: Error Source: IBMDA400 Command, Error Message: SQL0199: Keyword Update  not expected...* 

结果应该用来自CTE〃的数据更新tbl1中的匹配行;tableSQLFrmJoin">
现在,为了让查询工作起来,我只是使用设置案例的测试数据。

使用简单的,Select * from tableSQLFrmJoin按预期工作。因此,当使用select语句时,CTE在编写时是受支持的,并且工作正常。

您将需要类似这样的

update TBL1 t1
set STS = (select sts
from TBL1CPY cp
where cp.prj = t1.prj AND cp.PN = t1.PN AND cp.IN = t1.IN
)
where LDT = '20220104' AND US ='ADMIN';

请注意,上面假设总是有一个匹配行,或者如果没有匹配行,STS可以为null。

如果没有匹配的行并且STS不能为空,那么您将需要

update TBL1 t1
set STS = (select sts
from TBL1CPY cp
where cp.prj = t1.prj AND cp.PN = t1.PN AND cp.IN = t1.IN
)
where LDT = '20220104' AND US ='ADMIN'
and exists (select 1
from TBL1CPY cp
where cp.prj = t1.prj AND cp.PN = t1.PN AND cp.IN = t1.IN
);

最新更新