naroin
22nd February 2011, 15:58
hi,
i use a IDENTITY field in a SQL Server table, and i want to get the autogenerated value of the row i've just added.
my table is as follow :
create table MyTable
(IdTable INTEGER IDENTITY(1,1) NOT NULL PRIMARY KEY,
Name varchar(128) NOT NULL,
Value INTEGER NOT NULL);
my code is as follow :
db.transaction();
QSqlQuery query(db);
if (!query.exec("insert into MyTable (Name, Value) values ('A name', 1234);"))
{
QMessageBox::critical(this, "Db error", "DB error in INSERT statement : " + query.lastError().text());
db.rollback();
return;
}
if (!query.exec("SELECT SCOPE_IDENTITY()"))
{
QMessageBox::critical(this, "Db error", "DB error in SCOPE_IDENTITY statement : " + query.lastError().text());
db.rollback();
return;
}
if (query.next())
{
qDebug()<<"SCOPE_IDENTITY="<<query.value(0);
}
db.commit();
It seems that i get a result for "SELECT SCOPE_IDENTITY()", but it is always 0.
qDebug()<<query.value(0); always prints : "SCOPE_IDENTITY= QVariant(double, 0)"
while the real value generated is NOT 0.
Have anyone got the same problem?
thanks
i use a IDENTITY field in a SQL Server table, and i want to get the autogenerated value of the row i've just added.
my table is as follow :
create table MyTable
(IdTable INTEGER IDENTITY(1,1) NOT NULL PRIMARY KEY,
Name varchar(128) NOT NULL,
Value INTEGER NOT NULL);
my code is as follow :
db.transaction();
QSqlQuery query(db);
if (!query.exec("insert into MyTable (Name, Value) values ('A name', 1234);"))
{
QMessageBox::critical(this, "Db error", "DB error in INSERT statement : " + query.lastError().text());
db.rollback();
return;
}
if (!query.exec("SELECT SCOPE_IDENTITY()"))
{
QMessageBox::critical(this, "Db error", "DB error in SCOPE_IDENTITY statement : " + query.lastError().text());
db.rollback();
return;
}
if (query.next())
{
qDebug()<<"SCOPE_IDENTITY="<<query.value(0);
}
db.commit();
It seems that i get a result for "SELECT SCOPE_IDENTITY()", but it is always 0.
qDebug()<<query.value(0); always prints : "SCOPE_IDENTITY= QVariant(double, 0)"
while the real value generated is NOT 0.
Have anyone got the same problem?
thanks