DB2 SQL更新使用3个表,更新1个表,与另外2个表连接以选择要更新的行

rsaldnfx  于 2022-11-07  发布在  DB2
关注(0)|答案(2)|浏览(151)

我正在使用3个表。根据每个表中一个或多个字段的内容,我需要用常量数据更新其中的一个表。我的select可以很好地发现需要更新多少条记录,但似乎无法使更新生效。我的同事(有更多的DB2 SQL经验)给了我代码让我尝试。他的代码运行起来没有错误。但是没有正确地获取连接和“where”条件,从而只更新所需的记录--这样会更新太多的记录。
下面是工作正常的select:

select *
    from mylib.tabcp
inner join mylib.tabc c on cpactnum = c.actnum
inner join mylib.tabt t on cpactnum = t.actnum and cptagid = t.tagid
where (cpstatus = 'Active' and t.tagsts = 'P' and (c.actsts = 'A' or c.actsts = 'D'))

tabcp具有以下字段:cpactnumcp状态cptagid
tabc有:活动数活动
tabt具有:actnum标签ID标签
我需要更新tabcp中的一些字段,当:tabcp状态为活动状态,tabc状态为A或D,tabt状态为P
这是我的同事给我的更新-它运行了,没有得到任何错误,但没有正确选择要更新的记录。

update tabcp
set cpstatus = 'Inactive',
    cpdelstamp = current_timestamp,
    cpdeldate = current_date,
    cpdeltime = current_time,
    cpdeluser = current_user
where cpstatus = 'Active'
and cpactnum in 
 (select e.cpactnum from tabcp e
    inner join tabc c on e.cpactnum = c.actnum
    inner join tabt k on e.cpactnum = k.actnum
                     and e.cptagid = k.tagid
 where c.actsts in ('A','D') and k.tagsts = 'P')

我对DB2 SQL更新太不熟悉了,我尝试了各种各样的修改,到目前为止,我还没有得到正确的“组合”。
有人能帮帮我吗?
谢谢你,谢谢你

vu8f3i0k

vu8f3i0k1#

UPDATE mylib.tabcp p
set cpstatus = 'Inactive',
    cpdelstamp = current_timestamp,
    cpdeldate = current_date,
    cpdeltime = current_time,
    cpdeluser = current_user
WHERE EXISTS
(
SELECT 1
FROM mylib.tabc c, mylib.tabt t
WHERE
p.cpactnum = c.actnum
and p.cpactnum = t.actnum and p.cptagid = t.tagid
and p.cpstatus = 'Active' and t.tagsts = 'P' and c.actsts in ('A', 'D')
)
j9per5c4

j9per5c42#

请尝试此代码

enter code here
update tp
set cpstatus = 'Inactive',
cpdelstamp = current_timestamp,
cpdeldate = current_date,
cpdeltime = current_time,
cpdeluser = CURRENT_USER
from mylib.tabcp tp  
where cpstatus = 'Active'
and cpactnum in 
(select e.cpactnum from tabcp e
inner join tabc c on e.cpactnum = c.actnum
inner join tabt k on e.cpactnum = k.actnum
                 and e.cptagid = k.tagid
where c.actsts in ('A','D') and k.tagsts = 'P')

相关问题