简体   繁体   English

最佳实践:.NET:如何针对oracle数据库返回PK?

[英]Best practices: .NET: How to return PK against an oracle database?

With SQLServer, it seems to be generally accepted that adding a SELECT SCOPE_IDENTITY() to the end of your insert is the best way to return the PK of the newly-inserted record, assuming you're using an auto-increment field for the pk. 使用SQLServer,似乎普遍接受的是,在插入的末尾添加SELECT SCOPE_IDENTITY()是返回新插入记录的PK的最佳方法,假设您正在为pk使用自动增量字段。

However, I can't seem to find the equivalent for Oracle. 但是,我似乎无法找到Oracle的等价物。

Best practice seems to be to use a sequence to generate the PK, but there are different options for how to implement even that. 最佳实践似乎是使用序列来生成PK,但是如何实现甚至可以有不同的选项。 Do you leave it up to the developer to insert sequence.nexval, or use a trigger? 您是否将其留给开发人员插入sequence.nexval,或使用触发器?

In either case, getting the new ID back seems to be a common problem. 在任何一种情况下,获取新ID似乎是一个常见问题。

Suggestions and solutions I've run across include: 我遇到的建议和解决方案包括:

  • creating a stored proc that returns the PK 创建一个返回PK的存储过程
  • running a select id from seq.nextval, then passing that to the insert 从seq.nextval运行select id,然后将其传递给insert
  • select max(id) after insert (Note: Don't do this!) 插入后选择max(id)(注意:不要这样做!)
  • add a RETURNING clause to the insert 在插入中添加RETURNING子句

What should the "best practice" solution be for this situation? 对于这种情况,“最佳实践”解决方案应该是什么?

You can use the RETURNING clause to do this in Oracle stored procs. 您可以使用RETURNING子句在Oracle存储过程中执行此操作。

For example: 例如:

TABLEA has NAME and EMP_ID. TABLEA具有NAME和EMP_ID。 EMP_ID is populated internally when records are inserted. 插入记录时,内部填充EMP_ID。

INSERT INTO TABLEA(NAME) VALUES ('BOB') RETURNING EMP_ID INTO o_EMP_ID; INSERT INTO TABLEA(NAME)VALUES('BOB')将EMP_ID返回到o_EMP_ID;

That's assuming that line is in a stored proc with an output parameter of o_EMP_ID. 这是假设该行在存储过程中,输出参数为o_EMP_ID。

Hope that helps... if not, here's a more detailed example: 希望有帮助......如果没有,这里有一个更详细的例子:

http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/returninginto_clause.htm http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/returninginto_clause.htm

The RETURNING clause is intended for just this kind of usage, so I would call it a best practice to use it. RETURNING子句仅用于此类用法,因此我将其称为最佳实践。

An alternative would be to select seq.CURRVAL after the insert. 另一种方法是在插入后选择seq.CURRVAL。 That returns the last value obtained from the sequence by this session. 返回会话从序列中获取的最后一个值。

The stored procedure and the returning clause have the distinct benefit of a single database call any other solution is inferior. 存储过程和返回子句具有单个数据库调用的独特优点,任何其他解决方案都是劣等的。 Whether you do it via a stored procedure or you use a returning clause is a whole can of worms in itself. 无论您是通过存储过程来执行还是使用返回子句,本身就是一整套蠕虫。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM