简体   繁体   English

如何使用FireDac组件在MS SQL Server上获取最后插入的ID?

[英]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? 与FireDac,如何获取ms sql服务器上的最后插入的id? thanks 谢谢

Make the that id to a identity column and then get it by Using 使该id成为一个身份列,然后通过使用获取它

SELECT SCOPE_IDENTITY()

after the insert statement 在插入语句之后

Please refer the following links 请参考以下链接

http://msdn.microsoft.com/en-us/library/ms190315.aspx 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 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 另一种方法可能是制作适当的SQL语句,如


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 AnyDAC作者还建议通过http://docs.embarcadero.com/products/rad_studio/firedac/uADCompClient_TADCustomConnection_GetLastAutoGenValue@String.html获取特定于DBMS的工具的特殊方法。

But all those post-factum requests with SELECT @@identity or SELECT SCOPE_IDENTITY are fragile and dangerous. 但是所有带有SELECT @@identitySELECT SCOPE_IDENTITY事后请求都是脆弱且危险的。 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. 当您将数据插入表A中时,其触发器可能会将数据插入相关的表B和C中,标识将调用C的autoinc,而不是您从其开始插入的表。

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

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