上下文: 我有两个表:markettypewagerlimitgroups(mtwlg)和stakedistributionindicators(sdi)。当创建一个mtwlg时,在sdi表中创建了两行,这两行是链接到mtwlg的 - 每行都有相同的值bar 2,id和另一个字段(我们称之为列X),其中一行必须包含0另一个是1。 我们的代码库中存在一个错误,它可以自动防止这种情况的发生,所以在出现错误期间创建的任何mtwlg都没有相关的sdi,导致NPE在各个地方出现。Oracle SQL - 如何编写有条件和循环的插入语句?
为了解决这个问题,需要写一个补丁来循环遍历mtwlg表和每个ID,在sdi表中搜索2个相关的行。如果行存在,则不做任何事情;如果只有1行,请检查F是否为0或1,并插入另一个值;如果两行都不存在,则插入它们。这需要为每个mtwlg完成,并且还需要插入一个唯一的ID。
伪代码:
For each market type wager limit group ID
Check if there are 2 rows with that id in the stake distributions table, 1 where column X = 0 and one where column X = 1
if none
create 2 rows in the stake distributions table with unique id's; 1 for each X value
if one
create the missing row in the stake distributions table with a unique id
if 2
do nothing
如果有帮助的话 - 该修补程序将使用liquibase应用。
任何人有任何意见或想法,以及如何以及如何在SQL/liquibase补丁中写入?
在此先感谢您,让我知道您需要的任何其他信息。
编辑:
我实际上只是被告知要做到这一点使用PL/SQL,你有关于这个有什么想法/建议? 再次感谢。
*“我可以简单地使用MAX(d.id)+1”* NO!千万不要这么做:-)有很多原因会导致错误(主要是竞赛条件)。理想情况下,您将使用一个序列,例如正如[user boneist here]所建议的(http://stackoverflow.com/a/30233998/521799)。显式地或[通过触发器](http://stackoverflow.com/questions/25660307/creating-oracle-sequence-trigger) –
为了加速性能,你可以用一个虚拟2-行表/子查询 – Boneist
@Boneist:绝对!感谢提示 –