sql-server - 如何在使用 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 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 上发布此内容,但无法获得保存回复)
推荐阅读
- javascript - 如何防止 Mouse4 单击向后导航?
- sql - 根据值从表中获取范围
- asp.net-core - 带有 ASP.NET Core 3.1 Razor 页面的 Microsoft 身份平台中的可疑错误
- c++ - 在 gcc windows api 字符串处理中启用 UNICODE
- reactjs - 不能在 React-Native 中使用导航和道具?
- php - 如何以 symfony 1.4 形式读取默认值?
- python - 保存的 .wav 文件没有数据
- python - 如何遍历时间范围?
- arrays - 如何在c中将文本拆分为二维数组
- angular - 子路由中定义的组件不运行 NgOnInit 生命周期函数