确保该列遵循 Oracle 中的顺序

发布于 2024-09-28 03:50:13 字数 111 浏览 2 评论 0原文

有没有办法限制列(例如“ID”)遵循创建的序列(例如“ID_SEQ”)?

如果没有自动约束,手动插入可能会使整个序列变得不正常。可以采取什么措施来解决这个问题?只需调用 NextVal 两次?

Is there any way of constraining a column (say "ID") to follow a created sequence (say "ID_SEQ")?

Without an automatic constraint, manual inserts might throw the entire sequence out-of-whack. What can be done to fix this? Just call NextVal twice?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

So要识趣 2024-10-05 03:50:13

您可以使用触发器来完成此操作。例子:

create or replace trigger product_insert before insert on product for each row begin
select id_seq.nextval
into :new.product_id
from dual;
end;

You can use a trigger to accomplish this. Example:

create or replace trigger product_insert before insert on product for each row begin
select id_seq.nextval
into :new.product_id
from dual;
end;
柒夜笙歌凉 2024-10-05 03:50:13

没有办法为这种事情创建声明性约束。当然,您可以创建一个 BEFORE INSERT 行级触发器,该触发器将根据序列自动填充键(如果您担心不使用序列的临时插入,则忽略提供的任何值)。

如果您处于因某人临时插入创建的行且其键大于序列当前值而必须递增序列的情况,则您的两个选择是

  1. 创建一个循环,重复调用 nextval
  2. 更改序列以设置 INCREMENT BY到您需要的任何大值,调用一次 nextval ,然后将序列更改回来。不过,这要求没有其他人同时使用该序列。但如果您需要在从不同环境刷新数据后重置一堆序列之类的操作,那么它会很有用。

There is no way to create a declarative constraint for this sort of thing. You could, of course, create a BEFORE INSERT row-level trigger that would automatically populate the key based on the sequence (ignoring any value that was provided if you're concerned about ad hoc inserts that don't use the sequence).

If you are in a situation where you have to increment a sequence because someone's ad hoc inserts created rows with keys greater than the current value of the sequence, your two options are

  1. Create a loop that calls nextval repeatedly
  2. ALTER the sequence to set the INCREMENT BY to whatever large value you need, call nextval once, and ALTER the sequence back. This requires that no one else is using the sequence at the same time, though. But it is useful if you need to do something like reset a bunch of sequences after refreshing data from a different environment.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文