如何使用触发器获取序列中的下一个值

发布于 2024-09-28 06:50:57 字数 554 浏览 7 评论 0原文

我刚刚学习Oracle,我了解触发器和序列的概念。我似乎找不到的是它们如何以类似于 SqlServer Identity 设置的自动增量方式一起使用。在一个非常简单的示例中,我有一个名为“Employees”的表,其中包含三个字段(均为必需字段):EmployeeID (PK)、FirstName、LastName。我创建了一个序列来获取 ID 字段的下一个值。然后我创建了一个如下所示的触发器:

CREATE OR REPLACE TRIGGER MyFirstTrigger
 BEFORE INSERT ON EMPLOYEES  FOR EACH ROW
BEGIN
   Select EMP_SEQ.NextVal into :NEW.EMPLOYEEID from dual;
END MyFirstTrigger;
/

但是,它如何在插入语句中使用?仅包含 FirstName 和 LastName 值的插入语句因“值不足”而失败(顺便说一句,我正在使用 Toad)。如果我必须包含 EMP_SEQ.NextVal 作为插入语句的第一个值,那么触发器的意义何在?

希望这是有道理的。提前致谢。

I'm just learning Oracle and I understand the concept of triggers and sequences. What I can't seem to find is how they are used together in an auto-increment fashion similar to a SqlServer Identity setting. In a really simple example, I have a table called Employees that has three fields (all required): EmployeeID (PK), FirstName, LastName. I have created a sequence to get the next value for the ID field. I then created a trigger that looks like so:

CREATE OR REPLACE TRIGGER MyFirstTrigger
 BEFORE INSERT ON EMPLOYEES  FOR EACH ROW
BEGIN
   Select EMP_SEQ.NextVal into :NEW.EMPLOYEEID from dual;
END MyFirstTrigger;
/

However, how is this used in an insert statement? An insert statement with only the FirstName and LastName values fails for "Not enough values" (I'm using Toad, by the way). If I have to include EMP_SEQ.NextVal as the first value of the insert statement, what's the point of the trigger?

Hopefully, this makes sense. Thanks in advance.

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

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

发布评论

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

评论(2

单身狗的梦 2024-10-05 06:50:57

您可以省略插入中的 ID,但必须指定目标列:

insert into employees (firstname, lastname) values ('Tony', 'Andrews');

在生产代码中不应该有没有列列表的插入;但是如果你这样做了,你可以为 D 列传递 NULL:

insert into employees values (null, 'Tony', 'Andrews');

You can omit the ID from the insert, but you must specify the target columns:

insert into employees (firstname, lastname) values ('Tony', 'Andrews');

You should not have inserts without a column list in production code; however if you did you could just pass a NULL for the D column:

insert into employees values (null, 'Tony', 'Andrews');
清风夜微凉 2024-10-05 06:50:57

这应该有效,如果没有,我将描述其可能的原因和用法。

INSERT INTO EMPLOYEES (FirstName, LastName) VALUES ('Name', 'LastName')

并且你肯定能够做到这一点

   INSERT INTO EMPLOYEES (EMPLOYEEID , FirstName, LastName) VALUES (null, 'Name', 'LastName')

This should work if not i will describe the possible reason of that and usage.

INSERT INTO EMPLOYEES (FirstName, LastName) VALUES ('Name', 'LastName')

and for sure You will be able to do this

   INSERT INTO EMPLOYEES (EMPLOYEEID , FirstName, LastName) VALUES (null, 'Name', 'LastName')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文