首页 > 解决方案 > 如何在使用 TFDUpdateSQL 插入后获取新 AutoInc 字段值的值

问题描述

我试图从例如 SQL Server 使用 TFDUpdateSQL 时访问新生成的自动增量字段值。

缓存更新示例将其作为插入 SQL 包括在内:

INSERT INTO {id Products} (
  ProductName, SupplierID, CategoryID,
  QuantityPerUnit, UnitPrice, UnitsInStock, UnitsOnOrder,
  ReorderLevel, Discontinued)
VALUES (
  :NEW_ProductName, :NEW_SupplierID,
  :NEW_CategoryID, :NEW_QuantityPerUnit, :NEW_UnitPrice,
  :NEW_UnitsInStock, :NEW_UnitsOnOrder, :NEW_ReorderLevel,
  :NEW_Discontinued
)
{IF MSSQL} select :NEW_ProductID = @@identity {FI}
{IF MSAcc} select @@identity as ProductID {FI}
{IF MySQL} select LAST_INSERT_ID() as ProductID {FI}
{IF IB} returning ProductID {into :NEW_ProductID} {FI}
{IF PG} returning ProductID {into :NEW_ProductID} {FI}
{IF SQLite}; select LAST_INSERT_ROWID() as ProductID {FI}
{IF Ora} returning ProductID into :NEW_ProductID {FI}

但是,该示例没有使用NEW_ProductID代码中的结果(或我能确定的任何其他方式),并且表单上的数据表网格不反映 SQL Server 生成的新 ProductID 值。

我尝试从 TFDQuery 组件查看 TField,但该字段组件的 NewValue 属性中也没有新值。

如何访问和使用从代码中的 @@identity 检索到的新 AutoInc 值?

标签: sql-serverdelphifiredac

解决方案


我确实找到了解决方案,至少对于 SQL Server。事实证明,TFDUpdateSQL 组件生成的 InsertSQL 与示例中的 InsertSQL 不同。生成的代码包括INSERT INTO子句,后跟

SELECT SCOPE_IDENTITY() AS ProductID

如果我使用原始 INSERT INTO 子句,后跟该子句,那么我可以使用 TFDQuery 上的 TField 访问 OnUpdateRecord 处理程序中的新 AutoInc 值。新的 InsertSQL 是

INSERT INTO {id Products} (
  ProductName, SupplierID, CategoryID, 
  QuantityPerUnit, UnitPrice, UnitsInStock, UnitsOnOrder, 
  ReorderLevel, Discontinued)
VALUES (
  :NEW_ProductName, :NEW_SupplierID, 
  :NEW_CategoryID, :NEW_QuantityPerUnit, :NEW_UnitPrice, 
  :NEW_UnitsInStock, :NEW_UnitsOnOrder, :NEW_ReorderLevel, 
  :NEW_Discontinued
)

SELECT SCOPE_IDENTITY() AS ProductID

然后我可以在 onUpdateRecord 处理程序中访问新的 ProductID AutoInc 值,在 usProducts.Apply() 调用之后,使用

theIdField := qryProducts.FindField('ProductID');
theIdValue := theIdField.AsInteger;

当在 usProducts.Apply() 之前使用时,相同的代码还允许访问临时(预插入)AutoInc 值。

(注意:我尝试在 community.idera.com 上发布此内容,但无法获得保存回复)


推荐阅读