Informix: how to get an id of the last inserted record

旧巷老猫 提交于 2019-12-02 07:00:38

问题


What's the most efficient way of getting the value of the SERIAL column after the INSERT statement? I.e. I am looking for a way to replicate @@IDENTITY or SCOPE_IDENTITY functionality of MS SQL


回答1:


The value of the last SERIAL insert is stored in the SQLCA record, as the second entry in the sqlerrd array. Brian's answer is correct for ESQL/C, but you haven't mentioned what language you're using.

If you're writing a stored procedure, the value can be found thus:

LET new_id = DBINFO('sqlca.sqlerrd1');

It can also be found in $sth->{ix_sqlerrd}[1] if using DBI

There are variants for other languages/interfaces, but I'm sure you'll get the idea.




回答2:


I have seen this used.

if LOCAL_SQLCA^.sqlcode = 0 then
/ return serial */
  Result := LOCAL_SQLCA^.sqlerrd[1]
else
/* return error code */
  Result := -(Abs(LOCAL_SQLCA^.sqlcode));



回答3:


I don't think "efficient" is the word you're looking for here. It's more of a question of accuracy. I'm not sure I can do a better job of explaining it than the SQL Books Online can, but generally, unless you really know what you're doing and have a specific reason for using @@IDENTITY, use SCOPE_IDENTITY. The most obvious reason for this is that @@IDENTITY will not return the identity of the latest record added by your program/sp/etc if there is a trigger attached to the table. Also, there could be issues in high volume applications where two transactions occur at the same time and the following would occur...

  1. Your insert
  2. Other user's insert
  3. Return other user's identity to you



回答4:


The OP did not specify which version of Informix is being used, so there can be different answers



来源:https://stackoverflow.com/questions/246983/informix-how-to-get-an-id-of-the-last-inserted-record

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!