Clear Filters
Clear Filters

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 views (last 30 days)
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.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
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.

More Answers (0)

Products


Release

R14SP1

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!