How can the primary key of the last record that was inserted into a database using the FASTINSERT command in Database Toolbox 3.1 (R14SP3) be retrieved?
4 次查看(过去 30 天)
显示 更早的评论
In the following example, two records are inserted into a database that has three fields, valueA, valueB and ID, where ID is an auto-increment primary key field.
% connect to a database
conn = database('matlab_helper', '', '');
% insert two new records with some data
fastinsert(conn, 'run_data' , {'valueA' 'valueB'}, [10 200]);
fastinsert(conn, 'run_data' , {'valueA' 'valueB'}, [21 318]);
I would like to know how to retrieve the primary key, i.e., the ID value of the last inserted record.
采纳的回答
MathWorks Support Team
2009-6-27
The ability to retrieve the primary key of a record inserted via FASTINSERT is not available in Database Toolbox.
To work around this issue, create and run a query to retrieve the last generated ID. The SQL keywords WHERE and @@IDENTITY can help achieve this, as illustrated in the following example:
% connect to a database
conn = database('matlab_helper', '', '');
% insert two new records with some data
fastinsert(conn, 'run_data' , {'valueA' 'valueB'}, [10 200]);
fastinsert(conn, 'run_data' , {'valueA' 'valueB'}, [21 318]);
% generate query to select the ID of the last record, where ID is set up as an AUTO_INCREMENT field
q2 = ('select ID from run_data WHERE ID = @@IDENTITY');
% execute the query and retrieve the results
curs = exec(conn, q2);
curs = fetch(curs);
last_ID = curs.Data
close( conn );
The variable "last_ID" now contains the last generated ID value.
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Database Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!