简体   繁体   中英

How to get last inserted id on ms sql server with FireDac component?

with FireDac, How to get last inserted id on ms sql server? thanks

Make the that id to a identity column and then get it by Using

SELECT SCOPE_IDENTITY()

after the insert statement

Please refer the following links

http://msdn.microsoft.com/en-us/library/ms190315.aspx

Use auto-incremented field type

http://www.da-soft.com/anydac/docu/Auto-Incremental_Fields.html

This would provide for code like

DataSet.Insert;
.... 
DataSet.Post; 
id := DataSet.FieldByName('ID').AsInteger;

Another approach might be crafting proper SQL statements like described at


AnyDAC author also suggests a special method to fetch DBMS-specific toolings via http://docs.embarcadero.com/products/rad_studio/firedac/uADCompClient_TADCustomConnection_GetLastAutoGenValue@String.html

But all those post-factum requests with SELECT @@identity or SELECT SCOPE_IDENTITY are fragile and dangerous. When you insert data into table A, its triggers may insert data into related tables B and C, and identity would recall C's autoinc, rather than table where you started inserting at.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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