获取从 C# (oracle) 调用的插入语句使用的序列号
我需要在表中插入一条记录并将列的值(例如 orderid)设置为唯一的#。并返回所使用的号码。
我认为这个过程是使用一个序列和一个带有 nextval 的插入语句:
insert into ordersTable(orderid) values(ordernums.nextval);
但是如何获取所使用的数字?我的想法是我必须从插入调用中取回它,否则如果我重新查询,nextval(或currval)可能会改变。
但我不知道该怎么做。我认为解决这个问题的一种方法是,在插入时,还将我唯一的唯一值添加到字段中,然后重新查询该值。
还有其他方法可以做到这一点吗?我想我可能在 sql 级别遗漏了一些东西?
CtC
I need to insert a record into a table and set the value of a column (e.g. orderid) to a unique #. And return that number used.
I thought the process would be to do use a sequence and an insert statement with nextval:
insert into ordersTable(orderid) values(ordernums.nextval);
But how to I get the number that was used? My thought is that I have to get it back from the insert call otherwise the nextval (or currval) could have changed if I re-query.
But I'm not sure how to do that. One way around this I thought would be to, on insert, also add my only unique value to a field, then requery for that value.
Is there another way to do this? I figure I probably missing something at the sql level?
CtC
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我所知,Oracle 9i+ 有 RETURNING 子句:
另一种方法是在 INSERT 语句之前填充变量:
在函数内:
使用 OUT 参数:
此外,请注意序列的 CURRVAL 是特定于会话的。无论您在当前会话中调用 NEXTVAL 已有多长时间,也无论有多少其他会话可能对同一序列调用了 NEXTVAL,ordernums.currval 将始终返回为您的会话提供的序列的最后一个值。因此,尽管您有多种选项可以从 INSERT 中检索值,但这可能不是必需的 - 您可能只想在后续语句中引用 ordernums.currval。当然,由于 CURRVAL 是特定于会话的,因此如果您在为同一序列调用 NEXTVAL 之前在会话中调用 CURRVAL,则没有意义(并且会返回错误)。
Far as I know, Oracle 9i+ has the RETURNING clause:
The alternative is to populate the variable before the INSERT statement:
Within a function:
Using an OUT parameter:
In addition, be aware that the CURRVAL of a sequence is session-specific. No matter how long since you called NEXTVAL in the current session and no matter how many other sessions may have called NEXTVAL on the same sequence, ordernums.currval will always return the last value of the sequence that was given to your session. So although you have various options for retrieving the value from the INSERT, it may not be necessary-- you may simply want to reference ordernums.currval in subsequent statements. Of course, since CURRVAL is session-specific, it does not make sense (and would return an error) if you called CURRVAL in a session before you had called NEXTVAL for the same sequence.