如何使用相同的序列值更新多行
我正在使用 DB2,并且想要使用序列中的相同下一个值来更新满足我的条件的几行。 这是我尝试过的方法,但这不起作用,因为为每行获取下一个值:-
update dependency dep set vid=NEXT VALUE FOR seq_VID where id in ('8371','8372','8373')
id 是主键,seq_VID 是序列。所以我所希望的是,下一个序列值是 99,那么 99 将为所有 3 行设置(而不是像这样的 99,100,101)。 我的解决方法是将其分为列表中每个 id 的单独语句,即,
update dependency dep set vid=NEXT VALUE FOR seq_VID where id= ('8371')
update dependency dep set vid=PREVIOUS VALUE FOR seq_VID where id= ('8372')
update dependency dep set vid=PREVIOUS VALUE FOR seq_VID where id= ('8373')
但如果可能的话,我想在一个 SQL 语句中执行它 - 有什么想法吗?
I'm using DB2 and want to update several rows that meet my condition with the same next value from my sequence.
Here is what I tried but this doesn't work as the next value is fetched for each row:-
update dependency dep set vid=NEXT VALUE FOR seq_VID where id in ('8371','8372','8373')
id is the the primary key and seq_VID is a sequence. So what I had hoped was that say the next sequence value was 99, that 99 would be set for all 3 rows (and not 99,100,101 as is the case with this).
My workaround is to break it into separate statements for each id in my list, i.e.
update dependency dep set vid=NEXT VALUE FOR seq_VID where id= ('8371')
update dependency dep set vid=PREVIOUS VALUE FOR seq_VID where id= ('8372')
update dependency dep set vid=PREVIOUS VALUE FOR seq_VID where id= ('8373')
But I'd like to execute this in one SQL statement if possible - any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您始终知道想要将“前一个”序列值放在使用“下一个”下一个值更新的行之后的两行上,则可以使用复合触发器,类似于以下内容(Oracle 语法,请原谅):
然后您将发出更新语句,
并且触发器应该负责更新其他两行。
复合触发器在 Oracle 11+ 中非常有用,可帮助解决“变异表”错误,当触发器尝试在触发器所在的同一个表中 SELECT、INSERT、UPDATE 或 DELETE 数据时会发生该错误。
这是一个相当人为的情况,并且对应该更新哪些行做出了一些巨大的假设,但也许它会被证明是有用的。
分享并享受。
If you always knew that you wanted to put the 'previous' sequence value on the two rows after the one you updated with the 'next' next value you might be able to use a compound trigger, similar to the following (Oracle syntax, please forgive):
Then you'd issue your update statement as
and the trigger should take care of updating the other two rows.
The compound trigger is useful in Oracle 11+ to help work around the 'mutating table' error, which occurs when a trigger attempts to SELECT, INSERT, UPDATE, or DELETE data in the same table which the trigger is on.
This is a rather contrived situation and makes some huge assumptions about which rows should be updated, but perhaps it will prove useful.
Share and enjoy.