coldfusion - 如何在 Coldfusion 2021 脚本中为 MSSQL "insert"查询获取生成的 key ?

标签 coldfusion cfml

问题
我想从 SQL 查询中获取插入行的 id:

INSERT INTO NameList (Name) VALUES('John')
我需要在 Coldfusion 2021 脚本中执行此操作,如下所示:
var sqlQuery = "INSERT INTO NameList (Name) VALUES(?)";
var params = [{ value: "John", cfsqltype: "cf_sql_varchar" }];

try {
    var executedQuery = queryExecute(sqlQuery, params, {/* ...other options... */});
    
    //This is where it fails, because getResult() returns NULL.
    var insertedId = executedQuery.getResult().GENERATEDKEY;
}
catch (any ex) {
    //...report the error, read ex.message
}
但这不起作用,因为 getResult() 返回 NULL。
研究
我读过获取数据的正确方法不是通过 getResult() ,但与 getPrefix() 从这个 StackOverflow 答案:getting result metadata from coldfusion newQuery() in cfscript
但这不起作用, getPrefix() 也返回NULL。我在 CFDocs.org 或 Adob​​e 的文档中找不到有关此功能的文档(尽管 Adob​​e 的文档对我来说很难浏览)。
getPrefix() 函数在 cffiddle.org 上也不起作用,所以我无法以其他方式对其进行测试。
临时解决方案
我已经能够使用我试图避免的样式获取插入行的 id:传入一个命名的 结果 变量通过 queryExecute 的选项参数。
//...clipped...
try {
    //The options.result parameter is set to 'queryResult'.
    var executedQuery = queryExecute(sqlQuery, params, { result = "queryResult" });
    
    //This works, though I'm not sure where 'queryResult' exists in scope.
    var insertedId = queryResult.GENERATEDKEY;
}
//...clipped...
我不知道 queryResult 的范围是什么(它是全局的吗?),但这有效。我更喜欢传入局部变量,但传入 { result = "someLocalVar" }导致了错误。
有没有办法传入局部变量?我会发现这是可以接受的。
结论
我想使用 Coldfusion 2021 脚本获取插入行的 ID。我宁愿不使用 queryExecute() 的 options.result 参数,而是使用 getResult() 或类似的机制。
如果这是不可能的,那么我希望能够将局部变量传递给 queryExecute() 的 options.result 参数。
如果这是不可能的,那么我想至少知道 options.result 引用的变量的范围是什么。

最佳答案

var executedQuery = queryExecute(sqlQuery, params, { result = "queryResult" });
看看参数,你指定的结果是 queryResult。因此,它具有生成的 key 。
文档表明您不需要指定结果( https://helpx.adobe.com/coldfusion/cfml-reference/coldfusion-functions/functions-m-r/queryexecute.html )并且查询执行结果的重新结果/返回结果是结果,但这接缝无法按照 ACF2021 中的文档工作。
我会在下面建议。
try {
  var executedQuery = ''; 
  queryExecute(sqlQuery, params, { result = "executedQuery" });
  var insertedId = executedQuery.GENERATEDKEY;
}

关于coldfusion - 如何在 Coldfusion 2021 脚本中为 MSSQL "insert"查询获取生成的 key ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67713609/

相关文章:

asp.net - C# 部分类的 ColdFusion CFC 实现?

apache - 什么会导致带有 Railo 4 和 mod_cfml 的 tomcat 404 用于 SES urls like/index.cfm/event/main.home?

mysql - Coldfusion MySQL,FUNCTION 个人网站coldfusion.AddUser 不存在

coldfusion - 独特的 QoQ 自动应用订单

coldfusion - 应该使用哪个 EncodeFor 进行定位?

html - float div 的左侧或右侧取决于没有列的变量

pdf - Coldfusion/DDX PDF 单页书签

javascript - Javascript 中的 CFML

java - 在没有方法参数的情况下直接调用 cfc 时 ColdFusion 内存泄漏

ColdFusion 变量竞争条件?