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!