Page 1 of 1

Insert with returning and zquery open

Posted: 28.05.2017, 08:05
by danielsap
Hi,

I'm trying to insert a new record in table and get the generated by sequence value of Id column.
So, I found that the right approach is to use insert with returning.
I did it but after executing 2 things happen
1 - I receive the newly generated id
2 - There is no new record in the table.

It looks like it performs some action but at the end inserted data is removed.
I tried to use commitupdates but with no success.

Here is the code

query := TZQuery.Create(nil);
query.Connection := dbConnection;
query.SQL.Add('INSERT INTO BODY_TABLE (Name, Comment) VALUES (:pName, :pComment) returning TableId');
query.ParamByName('pName').Value := szName;
query.ParamByName('pComment').Value := szInfo;
query.Open;

// query.First;
newId := query.FieldByName('TableId').AsInteger;
if newId = 0 then
ShowMessage('Newid is 0');
query.Close;
query.Free;

I'm using
Zeos 7.2.1-rc
Firebird-3.0.2.32703-0_Win32
Delphi XE3

Thanks
Daniel

Re: Insert with returning and zquery open

Posted: 30.05.2017, 08:08
by marsupilami
Hello Daniel,

I tested this yesterday. It seems to be some kind of transaction handling issue with Zeos. The following code should work for you:

Code: Select all

query := TZQuery.Create(nil);
query.Connection := dbConnection;
query.SQL.Add('INSERT INTO BODY_TABLE (Name, Comment) VALUES (:pName, :pComment) returning TableId');
query.ParamByName('pName').Value := szName;
query.ParamByName('pComment').Value := szInfo;
query.Connection.StartTransaction;
try
  query.Open;

  // query.First;
  newId := query.FieldByName('TableId').AsInteger;
  if newId = 0 then
  ShowMessage('Newid is 0');
  query.Close;
  query.Connection.Commit;
except
  query.Connection.Rollback;
end;
query.Free;
Maybe it makes more sense to use standalone generators/sequences and TZSequence?

With best regards,

Jan