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 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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.
Respuesta aceptada
MathWorks Support Team
el 27 de Jun. de 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.
0 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Database Toolbox en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!