To add a new record in MS SQL database table I used a TADOTable
component and it's Append
and Post
methods.
My table contains ID
column ( PK, auto-increment
) and after I execute Post
method, I need to know what ID
value is assigned in the new record.
How to do it?
Use TDOQuery
component with OUTPUT
clause to insert the data and return the ID
s as
AQ.Close;
AQ.SQL.Clear;
AQ.SQL.Add('INSERT INTO Table (Col1, Col2) OUTPUT INSERTED.ID VALUES (:Param1, :Param2)');
AQ.Parameters.ParamByName('Param1').Value:= SomeValue;
AQ.Parameters.ParamByName('Param2').Value:= SomeValue;
AQ.Open;
Note that you need to use Open
method instead of ExecSQL
to return the results.
You can also use SCOPE_IDENTITY
and you will need to create a parameter to return the value for you, and assign pdReturnValue
to the Direction
of that parameter
Var InsertedID: Integer;
...
AQ.Close;
AQ.SQL.Clear;
AQ.SQ.Add('INSERT INTO Table (Col1, Col2) VALUES (:Param1, :Param2);');
AQ.SQL.Add('SET :ID = SCOPE_IDENTITY()');
AQ.Parameters.ParamByName('Param1').Value:= SomeValue;
AQ.Parameters.ParamByName('Param2').Value:= SomeValue;
AQ.Parameters.ParamByName('ID').Direction:= pdReturnValue
AQ.ExecSQL;
InsertedID:= AQ.Parameters.ParamByName('ID').AsInteger;
AQ in the example is a TADOQuery
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.