bool ok = query.exec("CREATE TABLE person ( IdTable INTEGER IDENTITY(1,1) NOT NULL PRIMARY KEY, LastName varchar(255), FirstName varchar(255) )");
bool ok1 = query.exec("INSERT INTO person VALUES ('Wijethilake','Tharanga')");
QSqlQuery scope_Identity("SELECT SCOPE_IDENTITY() AS Current_Identity;");
QSqlRecord rec = scope_Identity.record();
qDebug() << scope_Identity.isValid();
This returns false. IS it that something wrong with qt or is my scope Identity statement wrong. I really appreciate someone’s help on this.
Thank you.
This may be related to how QSqlQuery operates.
I don’t know QSqlQuery, but I have had a similar issue with
SCOPE_IDENTITY()in other languages where theINSERTandSELECT SCOPE_IDENTITY()...statements are run in different scopes – meaning that the results of theINSERTare not accessible toSCOPE_IDENTITY()– typically because they are executed as dynamic SQL by the data access layer. You can validate this by running a SQL trace on your database server forSQL:BatchCompletedevents.Assuming this is the issue, you need to execute both statements in the same scope to return the new identity. I’m not sure if this is valid QSqlQuery, but something like
In SQL 2005 and later, an alternative to
SCOPE_IDENTITY()is theOUTPUTclause, which enables you to do the whole thing in one statement: