我有Insert语句,该语句应返回Auto Increment列值。这是我的插入示例:
myQuery = new query();
myQuery.name = "insertRec";
myQuery.setDatasource("db");
mySQL = "
INSERT INTO myTable (
First, Last, Email, ActionDate
)VALUES(
:first, :last, :email, :actiondt
)
";
myQuery.setSQL(mySQL);
myQuery.addParam(name="first", cfsqltype="cf_sql_varchar", value="#trim(form.first)#", maxlength="50");
myQuery.addParam(name="last", cfsqltype="cf_sql_varchar", value="#trim(form.last)#", maxlength="50");
myQuery.addParam(name="email", cfsqltype="cf_sql_varchar", value="#trim(form.email)#", maxlength="320");
myQuery.addParam(name="actiondt", cfsqltype="cf_sql_timestamp", value="#now()#");
myQuery.execute().getResult();
//result = myQuery.execute().getResult(); This line is commented because I was getting error message that test variable is not defined. Not sure why since test is declared and equals to myQuery.execute().getResult();
运行后,此代码记录将出现在表中。结果集如下:
RecordID First Last Email ActionDt
7 John Woss jwoss@gmail.com 16-NOV-18
您会看到RecordID
(自动递增)在那里。我想在myQuery完成后获得该值。如何实现?
答案 0 :(得分:0)
如https://stackoverflow.com/a/34894454/432681中所述,您可以通过相关序列上的SELECT检索自动递增的ID。
因此,您的查询应如下所示:
mySQL = "
INSERT INTO myTable (
First, Last, Email, ActionDate
)VALUES(
:first, :last, :email, :actiondt
);
SELECT "sequenceForMyTable".currval from dual;
";
上面的链接答案中也描述了如何获得序列的名称。
https://stackoverflow.com/a/25268870/432681和mentioned in the CFML documentation中还概述了第二种方法,它表示您可以使用getPrefix()
函数来访问生成的密钥。请注意,在这种情况下,result
是execute()
方法返回的对象,而不是getResult()
返回的对象(因为查询不会返回结果集)。因此,对于您的示例,这是获取ID的方法:
result = myQuery.execute();
newID = result.getPrefix().generatedKey;